[英](solved)IO exception The process cannot access the file because it is being used by another process
I'm trying to delete a line from a txt file with my program, but the program has the text file open so I can't.我正在尝试使用我的程序从 txt 文件中删除一行,但是程序打开了文本文件,所以我不能。 What do I do?
我该怎么办?
private void btnDeleteTransaction_Click(object sender, EventArgs e)
{
string line = null;
string delete = txtDeleteTransId.Text;
using (reader = new StreamReader(txtFilePath.Text))
{
try {
using (writer = new StreamWriter(txtFilePath.Text, true))
{
while ((line = reader.ReadLine()) != null)
{
if (String.Compare(line + "|", delete) == 0)
continue;
writer.WriteLine(line);
}
}
}
catch (Exception ex)
{
txtMessages.Text = "exception deleting transaction: " + ex.Message;
}
}
}
Figured it out below.下面想通了。
I'm dumb and was trying to write from the reader which you can't do.我很笨,试图从读者那里写你做不到的。 Here is my working code if anyone is as new as me.
如果有人像我一样新,这是我的工作代码。
private void btnDeleteTransaction_Click(object sender, EventArgs e)
{
List<string> records = new List<string>();
found = false;
using (reader = new StreamReader(txtFilePath.Text))
{
while (!reader.EndOfStream)
{
record = reader.ReadLine();
if (record.StartsWith(txtDeleteTransId.Text + "|"))
{
found = true;
}
else
{
records.Add(record);
}
}
if (!found)
{
txtMessages.Text = "Record ID was not found";
return;
}
}
try
{
using (writer = new StreamWriter(txtFilePath.Text, false))
{
foreach (var item in records)
{
writer.WriteLine(item);
}
}
txtMessages.Text = "Record deleted";
}
catch (Exception ex)
{
txtMessages.Text = "exception deleting record: " + ex.Message;
}
}
```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.