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

C#将文件复制到另一个具有不同名称的位置,c#,file-io,C#,File Io,如果满足某些条件,我希望将文件从一个目录复制到另一个目录,而不删除原始文件。我还想将新文件的名称设置为特定值 我使用的是C#和FileInfo类。而它确实有CopyTo方法。它没有给我设置文件名的选项。MoveTo方法允许我重命名文件,同时删除原始位置的文件 最好的方法是什么?使用该方法 System.IO.File.Copy(oldPathAndName, newPathAndName); 例如 您可以在新文件中随意调用它,它将相应地重命名它。您也可以尝试以下方法: 您可以使用File.Co

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

我使用的是C#和FileInfo类。而它确实有CopyTo方法。它没有给我设置文件名的选项。MoveTo方法允许我重命名文件,同时删除原始位置的文件

最好的方法是什么?

使用该方法

System.IO.File.Copy(oldPathAndName, newPathAndName);
例如

您可以在新文件中随意调用它,它将相应地重命名它。

您也可以尝试以下方法:


您可以使用File.Copy(oldFilePath,newFilePath)方法或其他方法,即使用StreamReader将文件读入字符串,然后使用StreamWriter将文件写入目标位置

您的代码可能如下所示:

StreamReader reader = new StreamReader("C:\foo.txt");
string fileContent = reader.ReadToEnd();

StreamWriter writer = new StreamWriter("D:\bar.txt");
writer.Write(fileContent);
您可以添加异常处理代码…

您可以在System.IO.File类中使用该方法。

一种方法是:

File.Copy(oldFilePathWithFileName, newFilePathWithFileName);
或者,您也可以使用以下方法:

FileInfo file = new FileInfo(oldFilePathWithFileName);
file.CopyTo(newFilePathWithFileName);
例如:

File.Copy(@"c:\a.txt", @"c:\b.txt");


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


您可以使用的最简单方法是:

System.IO.File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);
这会满足您的所有要求

File.Copy(@"C:\oldFile.txt", @"C:\newFile.txt", true);
请不要忘记覆盖上一个文件!确保添加了第三个参数。通过添加第三个参数,可以覆盖文件。否则,可以对异常使用try-catch

问候,,
G

你不需要读写器,只需要流就可以了。也;如果您只复制(默认)流,NTFS替代流和审计/安全之类的内容将不会被复制。@March Gravel,谢谢您的输入。我对NTFS替代流知之甚少。。猜测需要了解它。请注意reader.ReadToEnd()会将所有文件内容加载到内存中。理论上可以接受的最大文件大小是2GB,但即使是(相对)较小的文件,这也可能是一个问题,特别是当您的进程内存不足时。
FileInfo file = new FileInfo(@"c:\a.txt");
file.CopyTo(@"c:\b.txt");
             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));
             }
StreamReader reader = new StreamReader(Oldfilepath);
string fileContent = reader.ReadToEnd();

StreamWriter writer = new StreamWriter(NewFilePath);
writer.Write(fileContent);
System.IO.File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);
File.Copy(@"C:\oldFile.txt", @"C:\newFile.txt", true);