Adr*_*der 80
使用File.Copy,您可以将新文件名指定为目标字符串的一部分.
所以像
File.Copy(@"c:\test.txt", @"c:\test\foo.txt");
Run Code Online (Sandbox Code Playgroud)
我试图将xml文件从一个位置复制到另一个位置.这是我的代码:
public void SaveStockInfoToAnotherFile()
{
string sourcePath = @"C:\inetpub\wwwroot";
string destinationPath = @"G:\ProjectBO\ForFutureAnalysis";
string sourceFileName = "startingStock.xml";
string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}
Run Code Online (Sandbox Code Playgroud)
然后我在一定间隔的timer_elapsed函数中调用了这个函数,我认为你不需要看.有效.希望这可以帮助.
是.它将工作:FileInfo.CopyTo方法
使用此方法允许或阻止覆盖现有文件.使用CopyTo方法可以防止默认情况下覆盖现有文件.
所有其他答案都是正确的,但既然你要求FileInfo
,这里是一个样本:
FileInfo fi = new FileInfo(@"c:\yourfile.ext");
fi.CopyTo(@"d:\anotherfile.ext", true); // existing file will be overwritten
Run Code Online (Sandbox Code Playgroud)