【发布时间】:2014-08-28 19:51:01
【问题描述】:
如果满足某些条件,我想将文件从一个目录复制到另一个目录而不删除原始文件。我还想将新文件的名称设置为特定值。
我正在使用 C# 并且正在使用 FileInfo 类。虽然它确实有 CopyTo 方法。它没有给我设置文件名的选项。而 MoveTo 方法在允许我重命名文件的同时,会删除原始位置的文件。
最好的方法是什么?
【问题讨论】:
如果满足某些条件,我想将文件从一个目录复制到另一个目录而不删除原始文件。我还想将新文件的名称设置为特定值。
我正在使用 C# 并且正在使用 FileInfo 类。虽然它确实有 CopyTo 方法。它没有给我设置文件名的选项。而 MoveTo 方法在允许我重命名文件的同时,会删除原始位置的文件。
最好的方法是什么?
【问题讨论】:
System.IO.File.Copy(oldPathAndName, newPathAndName);
【讨论】:
你也可以试试Copy方法:
File.Copy(@"c:\work\foo.txt", @"c:\data\bar.txt")
【讨论】:
【讨论】:
如果你只想使用 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));
}
【讨论】:
一种方法是:
File.Copy(oldFilePathWithFileName, newFilePathWithFileName);
或者你也可以像这样使用FileInfo.CopyTo() 方法:
FileInfo file = new FileInfo(oldFilePathWithFileName);
file.CopyTo(newFilePathWithFileName);
例子:
File.Copy(@"c:\a.txt", @"c:\b.txt");
或
FileInfo file = new FileInfo(@"c:\a.txt");
file.CopyTo(@"c:\b.txt");
【讨论】:
StreamReader reader = new StreamReader(Oldfilepath);
string fileContent = reader.ReadToEnd();
StreamWriter writer = new StreamWriter(NewFilePath);
writer.Write(fileContent);
【讨论】:
File.Copy(@"C:\oldFile.txt", @"C:\newFile.txt", true);
请不要忘记覆盖之前的文件!确保添加第三个参数。通过添加第三个参数,您允许覆盖文件。否则,您可以对异常使用 try catch。
问候, G
【讨论】:
您可以在 System.IO.File 类中使用Copy 方法。
【讨论】:
您可以使用的最简单的方法是:
System.IO.File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);
这将处理您请求的所有内容。
【讨论】:
您可以使用 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);
可以添加异常处理代码...
【讨论】: