如何在c#中修改之前备份文本文件?

时间:2018-01-14 08:07:59

标签: c#

在将其修改为安全措施之前,如何制作文本文件的备份副本(可能是扩展名* .txt,* .xml,* .html)? 我试过了

string xml = File.ReadAllText(@"D:\MyFolder\test.txt");
string path=@"D:\MyFolder\test.bk";
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(xml);
tw.Close();
//code for modification of the original file i.e. "D:\MyFolder\test.txt"
File.WriteAllText(@"D:\MyFolder\test.txt", filecontentAsaString_after_modification);

但是获得异常 System.IO.IOException:进程无法访问文件'D:\ MyFolder \ test.bk',因为它正由另一个进程使用。。 应该很容易......我做错了什么?

1 个答案:

答案 0 :(得分:2)

最好使用Copy之类的:

string xml = File.ReadAllText(@"D:\MyFolder\test.txt");
string path = @"D:\MyFolder\test.bk";
File.Copy(@"D:\MyFolder\test.txt", path); 
TextWriter tw = new StreamWriter(path);
tw.WriteLine(xml);
tw.Close(); 
File.WriteAllText(@"D:\MyFolder\test.txt",filecontentAsaString_after_modification );

如果上面的代码运行两次,你将得到

的异常
  

文件'D:\ MyFolder \ test.bk'已经存在。

要避免将thrid参数传递给Copy以将其替换为:

File.Copy(@"D:\MyFolder\test.txt", path,true);