Rename File open by self
My program is logging data to a file, at the same time a user interface displays the incoming data live. I want the logged data to be on disk within a second or two if computer/program/os/whatever shuts down. Data is coming in at least 100 times/sec.
I want the user to be able to give the log-file a new name, while logging is active. The problem is that i can't change the name of the file while it is open, even if it is by the same process.
Test case:
string fileName1 = "test.txt";
string fileName2 = "test2.txt";
using (StreamWriter sw = new StreamWriter(new FileStream(fileName1, FileMode.Create)))
{
sw.WriteLine("before");
File.Move(fileName1, fileName2); //<<-- IOException - The process cannot access the file because it i开发者_开发问答s being used by another process.
w.WriteLine("after");
}
So, How do i rename a file from a process while the same process is having a stream to the file open?
You should close the first stream, rename the file, then reopen the stream:
using (StreamWriter sw = new StreamWriter(new FileStream(fileName1, FileMode.Create)))
{
sw.WriteLine("before");
sw.Close();
}
File.Move(fileName1, fileName2);
using (StreamWriter sw = new StreamWriter(new FileStream(fileName2, FileMode.Append)))
{
sw.WriteLine("after");
}
I know this answer is a bit late to help you on your porting project but perhaps it will help others!
If you open the file with the FileShare.Delete
flag it will let you rename it even though it is still open :)
You can't rename a file while it is open by a process, but if you want to write to it from the other instance of your program, do this.
Try FileShare.Write. You can use it in File.Open.
using (StreamWriter sw = new StreamWriter (File.Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
{
...
}
Opening en closing the file 100 times a second will have a impact on your performance, you can log to a temp file and append the temp file every 10 seconds or so. That will give you what you want.
精彩评论