StreamWriter/StreamReader File In Use By Another Process

时光总嘲笑我的痴心妄想 提交于 2019-12-13 13:21:50

问题


I have a StreamWriter object to write to a log file, it is initialised as follows:

StreamWriter streamWriter = File.AppendText(GetLogFilePath());
streamWriter.AutoFlush = true;

Later in my code, I need to close the log file, and then read in part of the logged out contents. I have the following code:

streamWriter.Close();
streamWriter = null;
StreamReader logFileStream = File.OpenText(GetLogFilePath());

This is throwing an exception: The process cannot access the file because it is being used by another process.

Presumably, the problem is that the log file is not correctly closed when I close the StreamWriter.

Is there a better way to close a StreamWriter to ensure that the file it has open, is correctly closed?

UPDATE: I have resolved my issue. It was caused by an unrelated problem (where a separate application was accessing the file that I was trying to access). I am accepting Dmitry Martovoi's answer, as I think it is the most useful for other people who have a similar issue in the future; but an important note is that the solution does require the log file to be opened every time the log is written to, which can cause unnecessary overhead.


回答1:


I always wrap such code in a using statement

using (StreamWriter writer = File.AppendText(path)) 
{
   writer.WriteLine("This");
   writer.WriteLine("is Extra");
   writer.WriteLine("Text");
}

but for StreamWriter Close method doing exactly the same as Dispose.




回答2:


You should wrap each file operation in a using block:

using (StreamWriter s = new StreamWriter(/* your arguments here *\)) {
    // code that uses it here
}
// file is closed here



回答3:


Try using File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None);



来源:https://stackoverflow.com/questions/14458003/streamwriter-streamreader-file-in-use-by-another-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!