我想做一个执行此操作的 C# 应用程序:
- 选择一个文件夹
- 将该文件夹中的所有文件复制到该文件夹+/results/
非常简单,但无法让它工作。
这是我的代码:
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);
}
最佳答案
首先,创建目标目录,如果不存在
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
string destPath = Path.Combine(folderBrowserDialog1.SelectedPath, "results");
if(Directory.Exists(destPath) == false)
Directory.CreateDirectory(destPath);
然后在你的循环中
foreach (string file in files)
{
string path2 = Path.Combine(destPath, Path.GetFileName(file));
File.Move(file, path2);
}
请注意File.Move不能用于覆盖现有文件。
如果文件存在于目标目录中,您将收到 IOException。
如果您只想复制而不是移动,只需将 File.Move
语句更改为 File.Copy(file, path2, true);
。此重载将毫无疑问地覆盖目标目录中的文件。
关于c# - 如何将文件移动到子目录? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11171005/