前言
在工作中,我们有时候要在一些文件夹里挑选图片或是txt等文件移出来到其他地方,这时候一个一个找效率肯定是很慢的,这时我们可以通过写一个程序来快速批量移动。
一、程序源代码
using System;
using System.IO;
namespace get_all_files
{
class Program
{
static void Main(string[] args)
{
var fileHelper = new FileHelper();
//下面的*.txt修改为你要在文件夹移动的文件类型后缀,如是图片就是.jpg
fileHelper.GetFiles2("你将在里面查找的路径", "*.txt");
}
}
public class FileHelper
{
//此处修改为存放你将要移动的文件位置
string pathD = @"D:\bbbb\";
public void GetFiles2(string path,string searchPattern)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles(searchPattern);
foreach (FileInfo file in files)
{
string path2_name = pathD + file.Name;
string path1_name = file.FullName;
Copy(path1_name,path2_name);
Console.WriteLine(file.Name);
}
}
public void Copy(string pa1, string pa2)
{
FileInfo fi1 = new FileInfo(pa1);
FileInfo fi2 = new FileInfo(pa2);
try
{
fi1.CopyTo(pa2,true);
Console.WriteLine("{0} was copied to {1}.", pa1, pa2);
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
}
}
}
以上代码改好直接运行就好了
二、将以上代码变成一个程序
using System;
using System.IO;
namespace get_all_files
{
class Program
{
static void Main(string[] args)
{
var fileHelper = new FileHelper();
// fileHelper.GetFiles(args[0], "*.txt");
fileHelper.GetFiles2(args[0], "*.txt");
}
}
public class FileHelper
{
string pathD = @"D:\bbbb\";
//输出全名包含路径
public void GetFiles(string path,string searchPattern)
{
string[] files = Directory.GetFiles(path,searchPattern);
foreach (var file in files)
{
Console.WriteLine(file);
}
}
//功能更全
public void GetFiles2(string path,string searchPattern)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles(searchPattern);
foreach (FileInfo file in files)
{
string path2_name = pathD + file.Name;
string path1_name = file.FullName;
Copy(path1_name,path2_name);
Console.WriteLine(file.Name);
}
}
public void Copy(string pa1, string pa2)
{
FileInfo fi1 = new FileInfo(pa1);
FileInfo fi2 = new FileInfo(pa2);
try
{
fi1.CopyTo(pa2,true);
Console.WriteLine("{0} was copied to {1}.", pa1, pa2);
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
}
}
}
程序写好后右键重新生成,右键在资源管理器打开文件夹 进入bin Debug、net,下的 .exe程序,在cmd中打开输入命令就可运行