如何重写txt文件 - 为什么我的代码不起作用

时间:2017-04-01 19:02:32

标签: c# file url-rewriting temp

我想重写我的txt文件(我需要删除行)。我使用这段代码:

 string cesta3 = cesta + "database.txt";
 string file = new StreamReader(cesta3).ReadToEnd();

 var linesToKeep = File.ReadLines(cesta3)
    .Where(l => l != "Meno: " + textBox1.Text + " PN " + textBox2.Text);       

但我不知道如何使用相同名称保存我的文件。我试试这个:

 File.WriteAllLines(cesta3, linesToKeep); // <== exception

 var tempFile = Path.GetTempFileName();
 File.Move(tempFile + ".txt", cesta3);

但它抛出异常:

  

其他信息:访问路径&#34;&#39; C:\ Users \ Lenovo \ documents \ visual studio 2015 \ Projects \ attendancer \ attendancer \ bin \ Debug \ database.txt&#39;被拒绝。&#34;

我该怎么办?

2 个答案:

答案 0 :(得分:3)

此行代码会锁定文件并阻止其移动:string file = new StreamReader(cesta3).ReadToEnd();

修复:

  • 使用StreamReader
  • 阅读file文字后,您可以正确关闭using
  • 或者,因为样本中没有使用StreamReaderReadToEndfile变量)的结果,所以您只需删除该行。

旁注:File.Move在您完成第一个异常后会抛出更多异常,因为源文件不太可能存在 - 我不确定您尝试对该调用做了什么。

答案 1 :(得分:1)

您的代码未关闭StreamReader。您可以使用File.ReadAllText自动关闭它。

string cesta3 = cesta + "database.txt";
//string file = new StreamReader(cesta3).ReadToEnd();
string file = File.ReadAllText(cesta3);

var linesToKeep = File.ReadLines(cesta3)
    .Where(l => l != "Meno: " + textBox1.Text + " PN " + textBox2.Text);

File.WriteAllLines(cesta3, linesToKeep); // <== exception
var tempFile = Path.GetTempFileName();
File.Move(tempFile + ".txt", cesta3);