I\'ve been working on this small piece of code that seems trivial but still, i cannot really see where is the problem. My functions do a pretty simple thing. Opens a file, c
Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :
using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
{
fs.close();
}
using (StreamWriter sw = new StreamWriter(@"File.txt"))
{
sw.WriteLine("bla bla bla");
sw.Close();
}
After creating a file you must force the stream to release the resources:
//FSm is stream for creating file on a path//
System.IO.FileStream FS = new System.IO.FileStream(path + fname,
System.IO.FileMode.Create);
pro.CopyTo(FS);
FS.Dispose();
My reputation being too small to comment an answer, here is my feedback concerning roquen answer (using settings on xmlwriter to force the stream to close): it works perfectly and it made me save a lot of time. roquen's example requires some adjustment, here is the code that works on .NET framework 4.8 :
XmlWriterSettings settings = new XmlWriterSettings();
settings.CloseOutput = true;
writer = XmlWriter.Create(stream, settings);
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;
}
}