该进程无法访问该文件,因为它正被另一个进程使用
The process cannot access the file because it is being used by another procces
我需要删除 txt 文件中的特定行,这意味着我需要读取并重写整个文件而忽略特定行,我试过了,但我得到了未处理的异常(该进程无法访问该文件,因为它正在被另一个进程使用)。
我在可疑过程中使用的所有内容是:
1。这条线
IEnumerable<string> text = System.IO.File.ReadAllLines(@"C:\TreeView.txt");
我曾经将所有行放入 "string"
和这部分应该从 txt 中删除特定行的方法
string line = null;
string filePath = @"c:\TreeView.txt";
using (StreamReader reader = new StreamReader(filePath, true))
{
using (StreamWriter sw = new StreamWriter(filePath))
{
while ((line = reader.ReadLine()) != null)
{
if (String.Compare(line, obj) == 0)
continue;
sw.WriteLine(line);
}
}
}
问题出在第二部分,您打开文件进行读取,然后尝试打开文件进行写入。你可以简单地做这样的事情:
var text = System.IO.File.ReadAllLines(@"C:\TreeView.txt");
System.IO.File.WriteAllLines(@"C:\TreeView.txt",
text.Where(x => String.Compare(line, obj) != 0));
我需要删除 txt 文件中的特定行,这意味着我需要读取并重写整个文件而忽略特定行,我试过了,但我得到了未处理的异常(该进程无法访问该文件,因为它正在被另一个进程使用)。 我在可疑过程中使用的所有内容是:
1。这条线
IEnumerable<string> text = System.IO.File.ReadAllLines(@"C:\TreeView.txt");
我曾经将所有行放入 "string"
和这部分应该从 txt 中删除特定行的方法
string line = null; string filePath = @"c:\TreeView.txt"; using (StreamReader reader = new StreamReader(filePath, true)) { using (StreamWriter sw = new StreamWriter(filePath)) { while ((line = reader.ReadLine()) != null) { if (String.Compare(line, obj) == 0) continue; sw.WriteLine(line); } } }
问题出在第二部分,您打开文件进行读取,然后尝试打开文件进行写入。你可以简单地做这样的事情:
var text = System.IO.File.ReadAllLines(@"C:\TreeView.txt");
System.IO.File.WriteAllLines(@"C:\TreeView.txt",
text.Where(x => String.Compare(line, obj) != 0));