0

I'm working with files on C#, my cose is supposed to delete some lines from a file as mentioned here:

 var tmpFile = Path.GetTempFileName(); 
 var LinesToKeep = File.ReadLines(path).Where(l => l.StartsWith("removeme")==false);            
 File.WriteAllLines(tmpFile, LinesToKeep);
 File.Delete(path);
 File.Move(tmpFile,path);

but I'm getting an exception: IOException was unhandled when running my code saying:

The process can not access the file because it is being used by another process

in the instruction: File.Delete(path); How can check which process is using file, or there is another reason for my problem?

Mehdi Ben Hamida
  • 893
  • 4
  • 16
  • 38
  • [How do I find out which process is locking a file using .NET?](http://stackoverflow.com/questions/317071/how-do-i-find-out-which-process-is-locking-a-file-using-net) – stuartd Mar 28 '17 at 14:47

1 Answers1

1

use FileShare enumeration to instruct OS to allow other processes (or other parts of your own process) to access same file concurrently.

using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read))
{
}
Paulo
  • 577
  • 3
  • 8
  • 23