【问题标题】:How to copy-paste a file that already exists?如何复制粘贴已经存在的文件?
【发布时间】:2015-09-09 14:43:37
【问题描述】:

我使用这行简单的代码来复制粘贴文件:

File.Copy(filename, temp_file);

现在,如果一个文件已经存在,我想在复制到某个名称之前重命名它,该名称通过添加一些名称扩展名,如“copy1”“copy2”......与windows一样通过资源管理器进行复制粘贴时。如何以编程方式执行此操作?

【问题讨论】:

  • 要重命名现有文件还是新文件?

标签: c# file


【解决方案1】:

类似的东西:

    private static void MoveCopy(String source, String target) {
      // assuming that target directory exists

      if (!File.Exists(target))
        File.Copy(source, target);
      else
        for (int i = 1; ; ++i) {
          String name = Path.Combine(
            Path.GetDirectoryName(target),
            Path.GetFileNameWithoutExtension(target) + String.Format("(copy{0})", i) +
            Path.GetExtension(target));

          if (!File.Exists(name)) {
            File.Copy(source, name);

            break;
          }
        }
    }

...

  MoveCopy(filename, temp_file);

【讨论】:

  • @juharr:谢谢!我真的应该添加++i
【解决方案2】:

使用File.Exists方法检查文件是否存在。

要重命名文件,您可以尝试创建更多循环以检查 copy(1) 是否存在

【讨论】:

    【解决方案3】:

    您可以通过检查现有文件并为目标生成新名称来做到这一点,直到它未被占用,如下所示:

    public static IEnumerable<string> FallbackPaths(string path)
    {
        yield return path;
    
        var dir = Path.GetDirectoryName(path);
        var file = Path.GetFileNameWithoutExtension(path);
        var ext = Path.GetExtension(path);
    
        yield return Path.Combine(dir, file + " - Copy" + ext);
        for (var i = 2; ; i++)
        {
            yield return Path.Combine(dir, file + " - Copy " + i + ext);
        }
    }
    public static void SafeCopy(string src, string dest)
    {
        foreach (var path in FallbackPaths(dest))
        {
            if (!File.Exists(path))
            {
                File.Copy(src, path);
                break;
            }
        }
    }
    

    注意这个函数可以给你IOException(因为文件已经存在的原因),如果同时写入同名的文件。

    【讨论】:

      【解决方案4】:
      (File.Exists(fileName) ? "File exists." : "File does not exist.")
      

      【讨论】:

        【解决方案5】:

        这就是我所做的:

        int p = 0;
        while (File.Exists(temp_file))
        {
            temp_file = Path.GetTempPath() + @"temp_presentation" + p.ToString() + ".pptx";
            p++;
        }
        File.Copy(filename, temp_file);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-10
          • 1970-01-01
          • 1970-01-01
          • 2013-05-04
          相关资源
          最近更新 更多