c# - 如何将文件移动到子目录? C#

标签 c# .net

我想做一个执行此操作的 C# 应用程序:

  1. 选择一个文件夹
  2. 将该文件夹中的所有文件复制到该文件夹​​+/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/

相关文章:

c# - Web 服务方法签名更改为数据类型字符串 [] 的请求/响应对象

c# - 如何在 C# 中获取昨天和明天的日期时间

c# - 无法在 .NET(完整)4.5 控制台应用程序中加载 Rosyln 生成的 PCL 程序集

c# - 以最佳性能将数据插入 SQL Server

c# - System.PlatformNotSupportedException 在运行时编译 C# 代码 .NET Core

.net - 从支付网关回发时丢失 session

c# - PropertyInfo 上的 GetSetMethod 和 SetMethod 有什么区别?

c# - 从下拉列表中选择值时如何回发到 Controller 功能

C# CustomAttributeData 类到属性

.net - 自定义 html 帮助程序 : Create helper with "using" statement support