I need to remove specific line in txt file which means i need to read and rewrite the whole file leaving out the specific line , i tried but i get unhandled-exeption (The process cannot access the file because it is being used by another procces). All i used in the processes suspicious was :
1 . this line
IEnumerable<string> text = System.IO.File.ReadAllLines(@"C:\TreeView.txt");
which i used to get all lines into "string"
and this part of the method which supposed to delete specific line from 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);
}
}
}
The problem is in the second part where you are opening the file for reading and then trying to open it for writing. You could simply do something like this:
var text = System.IO.File.ReadAllLines(@"C:\TreeView.txt");
System.IO.File.WriteAllLines(@"C:\TreeView.txt",
text.Where(x => String.Compare(line, obj) != 0));