服务器D盘上传的文件过多,空间剩下很少了,于是想把里面部分文件,大概几万个文件转移到E盘,做了这个小工具。先查询出要转移的文件清单,保存在一个记事本中,如下所示:
接着读取文件名,一个个移动到指定目录中去,winform窗体布局及效果如下:
完整代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading; namespace FileMoveTools
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} #region 目录
private void btnBrowseSrcDir_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog dialog = new FolderBrowserDialog())
{
if (dialog.ShowDialog() == DialogResult.OK)
txtSrcDir.Text = dialog.SelectedPath;
}
} private void btnBrowseFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "Text (*.txt)|*.txt;";
openFileDialog.AddExtension = true;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtFile.Text = openFileDialog.FileName;
}
}
} private void btnSetDestDir_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog dialog = new FolderBrowserDialog())
{
if (dialog.ShowDialog() == DialogResult.OK)
txtDestDir.Text = dialog.SelectedPath;
}
}
#endregion private void btnOK_Click(object sender, EventArgs e)
{
Thread mythread = new Thread(MoveFile);
mythread.IsBackground = true;
mythread.Start();
} private void MoveFile()
{
string srcDir = txtSrcDir.Text.Trim();
string destDir = txtDestDir.Text.Trim();
string files = txtFile.Text.Trim(); #region 验证路径是否存在
if (!Directory.Exists(srcDir))
{
statusMsg.Text = "要迁移的目录不存在";
return;
}
if (!Directory.Exists(destDir))
{
statusMsg.Text = "迁移后的目录不存在";
return;
}
if (!File.Exists(files))
{
statusMsg.Text = "文件清单不存!";
return;
}
#endregion statusMsg.Text = "文件开始迁移..";
int count = 0;
using (StreamReader sr = new StreamReader(files, Encoding.UTF8))
{
string strline = null;
while ((strline = sr.ReadLine()) != null)
{
long diskFreeSpace = GetHardDiskFreeSpace("D");
if (diskFreeSpace <= 5)
{
statusMsg.Text = "硬盘空间剩下5GB,停止迁移文件.";
return;
} string sourceFileName = srcDir + "/" + strline;
string destFileName = destDir + "/" + strline;
if (File.Exists(sourceFileName))
{
count++;
statusMsg.Text = "当前迁移第 " + count + " 个文件"; File.Move(sourceFileName, destFileName);
}
}
}
this.Invoke(new Action(() =>
{
statusMsg.Text = "迁移了 " + count + " 个文件,完成";
}));
} /// <summary>
/// 获取指定驱动器的剩余空间总大小(单位为GB)
/// </summary>
/// <param name="str_HardDiskName">只需输入代表驱动器的字母即可 </param>
/// <returns> </returns>
private static long GetHardDiskFreeSpace(string str_HardDiskName)
{
long freeSpace = new long();
str_HardDiskName = str_HardDiskName + ":\\";
System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
foreach (System.IO.DriveInfo drive in drives)
{
if (drive.Name == str_HardDiskName)
{
freeSpace = drive.TotalFreeSpace / (1024 * 1024 * 1024);
}
}
return freeSpace;
}
}
}