我想做一个这样做的C#应用程序:
很简单,但不能让它工作.
这是我的代码:
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string file in files)
{
MessageBox.Show(Path.GetFullPath(file));
//string path=Path.Combine(Path.GetFullPath(file), "results");
//MessageBox.Show(path);
string path2 = Path.GetDirectoryName(file);
path2 = Path.Combine(Path.GetDirectoryName(file), @"results\");
path2 = Path.Combine(path2, file);
MessageBox.Show(path2);
}
Run Code Online (Sandbox Code Playgroud)
首先,创建目标目录(如果不存在)
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
string destPath = Path.Combine(folderBrowserDialog1.SelectedPath, "results");
if(Directory.Exists(destPath) == false)
Directory.CreateDirectory(destPath);
Run Code Online (Sandbox Code Playgroud)
然后进入你的循环
foreach (string file in files)
{
string path2 = Path.Combine(destPath, Path.GetFileName(file));
File.Move(file, path2);
}
Run Code Online (Sandbox Code Playgroud)
请注意,File.Move不能用于覆盖现有文件.
如果文件存在于目标目录中,您将收到IOException.
如果您只想复制而不是Move,只需更改File.Move
语句即可File.Copy(file, path2, true);
.此重载将无问题地覆盖目标目录中的文件.