Visual C#: Move multiple files with the same extensions into another directory

前提是你 提交于 2019-11-28 00:14:10

First get all the files with specified extension using Directory.GetFiles() and then iterate through each files in the list and move them to target directory.

//Assume user types .txt into textbox
string fileExtension = "*" + textbox1.Text;

string[] txtFiles = Directory.GetFiles("Source Path", fileExtension);

foreach (var item in txtFiles)
{
   File.Move(item, Path.Combine("Destination Directory", Path.GetFileName(item)));
}

Try this:

For copying files...

foreach (string s in files)
{
   File.Copy(s, "C:\newFolder\newFilename.txt");
}

for moving files

foreach (string s in files)
{
   File.Move(s, "C:\newFolder\newFilename.txt");
}

Example for Moving files to Directory:

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.txt"))
{
      Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}

will Move all the files from Desktop to Directory "TextFiles".

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!