guys. I've got a problem I can't solve: I have a 2 folders I choose with folderBrowserDialog and tons of files in source directory I need to move to the target directory. But, I have only to move files with a specific extension like .txt or any other extension I can get from textbox. So how can I do it?
Asked
Active
Viewed 1.4k times
8
-
Ruff Pseudo; DirectoryInfo(sourceDir + "*.somextension").GetFiles().Foreach( (a) => a.Move(targetDir)) – Marvin Smit May 02 '14 at 09:30
-
Can you explain how to or give a link where can I find it? – baRUSHek May 02 '14 at 09:31
2 Answers
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)));
}

Kurubaran
- 8,696
- 5
- 43
- 65
1
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
".

SHEKHAR SHETE
- 5,964
- 15
- 85
- 143