System.IO.IOException: file used by another process
Sounds like an external process (AV?) is locking it, but can't you avoid the problem in the first place?
private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
try
{
string contents = File.ReadAllText(file.FullName);
Console.WriteLine("input : {0}", contents);
contents = contents.Replace(extractedMethod, modifiedMethod);
Console.WriteLine("replaced String {0}", contents);
File.WriteAllText(file.FullName, contents);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
I realize that I is kinda late, but still better late than never. I was having similar problem recently. I used XMLWriter
to subsequently update XML file and was receiving the same errors. I found the clean solution for this:
The XMLWriter
uses underlying FileStream
to access the modified file. Problem is that when you call XMLWriter.Close()
method, the underlying stream doesn't get closed and is locking the file. What you need to do is to instantiate your XMLWriter
with settings and specify that you need that underlying stream closed.
Example:
XMLWriterSettings settings = new Settings();
settings.CloseOutput = true;
XMLWriter writer = new XMLWriter(filepath, settings);
Hope it helps.