如何重写txt文件-为什么我的代码不起作用
How to rewrite txt file-why my code doesn't work
我想重写我的 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);
但我不知道如何用相同的方式保存我的文件name.I试试这个:
File.WriteAllLines(cesta3, linesToKeep); // <== exception
var tempFile = Path.GetTempFileName();
File.Move(tempFile + ".txt", cesta3);
但它抛出异常:
Additional information: Access to the path "'C:\Users\Lenovo\documents\visual studio 2015\Projects\attendancer\attendancer\bin\Debug\database.txt' is denied."
我该怎么办?
这行代码锁定文件并防止其移动:string file = new StreamReader(cesta3).ReadToEnd();
。
修复:
- 您可以在使用
using
file
阅读 file
文本后正确关闭 StreamReader
- 或者,由于示例中没有任何内容使用
StreamReader
或 ReadToEnd
(file
变量)的结果,您可以简单地删除该行。
旁注:File.Move
将在您完成第一个异常后抛出更多异常,因为源文件不太可能存在 - 我不确定您尝试对该调用做什么。
我想重写我的 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);
但我不知道如何用相同的方式保存我的文件name.I试试这个:
File.WriteAllLines(cesta3, linesToKeep); // <== exception
var tempFile = Path.GetTempFileName();
File.Move(tempFile + ".txt", cesta3);
但它抛出异常:
Additional information: Access to the path "'C:\Users\Lenovo\documents\visual studio 2015\Projects\attendancer\attendancer\bin\Debug\database.txt' is denied."
我该怎么办?
这行代码锁定文件并防止其移动:string file = new StreamReader(cesta3).ReadToEnd();
。
修复:
- 您可以在使用
using
file
阅读file
文本后正确关闭StreamReader
- 或者,由于示例中没有任何内容使用
StreamReader
或ReadToEnd
(file
变量)的结果,您可以简单地删除该行。
旁注:File.Move
将在您完成第一个异常后抛出更多异常,因为源文件不太可能存在 - 我不确定您尝试对该调用做什么。