C#将文件复制到另一个名称不同的位置

sha*_*shi 53 c# file-io

如果满足某些条件,我想将文件从一个目录复制到另一个目录而不删除原始文件.我还想将新文件的名称设置为特定值.

我正在使用C#并使用FileInfo类.虽然它确实有CopyTo方法.它没有给我设置文件名的选项.而MoveTo方法允许我重命名文件,删除原始位置的文件.

最好的方法是什么?

Mar*_*ell 106

System.IO.File.Copy(oldPathAndName, newPathAndName);
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 29

您也可以尝试复制方法:

File.Copy(@"c:\work\foo.txt", @"c:\data\bar.txt")
Run Code Online (Sandbox Code Playgroud)


Iai*_*ard 10

请改用File.Copy方法

例如.

File.Copy(@"C:\oldFile.txt", @"C:\newFile.txt");
Run Code Online (Sandbox Code Playgroud)

你可以在newFile中随意调用它,它会相应地重命名它.

  • 谁投票支持,谁愿意详细说明? (2认同)

Asi*_*dri 9

如果你只想使用FileInfo类试试这个

             string oldPath = @"C:\MyFolder\Myfile.xyz";
             string newpath = @"C:\NewFolder\";
             string newFileName = "new file name";
             FileInfo f1 = new FileInfo(oldPath);
           if(f1.Exists)
             {
                if(!Directory.Exists(newpath))
                {
                    Directory.CreateDirectory(newpath); 
                }
                 f1.CopyTo(string.Format("{0}{1}{2}", newpath, newFileName, f1.Extension));
             }
Run Code Online (Sandbox Code Playgroud)


Man*_*ish 5

一种方法是:

File.Copy(oldFilePathWithFileName, newFilePathWithFileName);
Run Code Online (Sandbox Code Playgroud)

或者您也可以使用FileInfo.CopyTo()方法,如下所示:

FileInfo file = new FileInfo(oldFilePathWithFileName);
file.CopyTo(newFilePathWithFileName);
Run Code Online (Sandbox Code Playgroud)

例子:

File.Copy(@"c:\a.txt", @"c:\b.txt");
Run Code Online (Sandbox Code Playgroud)

或者

FileInfo file = new FileInfo(@"c:\a.txt");
file.CopyTo(@"c:\b.txt");
Run Code Online (Sandbox Code Playgroud)