的StreamWriter / StreamReader的文件在由另一个进程使用 [英] StreamWriter/StreamReader File In Use By Another Process
问题描述
的StreamWriter的StreamWriter =文件:我有一个StreamWriter对象写入到一个日志文件,如下所示它被初始化。 AppendText通过(GetLogFilePath());
streamWriter.AutoFlush = TRUE;
后来在我的代码,我需要关闭日志文件,然后在登录的部分内容出的内容。我有以下代码:
streamWriter.Close();
的StreamWriter = NULL;
的StreamReader logFileStream = File.OpenText(GetLogFilePath());
这是抛出一个异常:
的该进程无法访问,因为它的文件正在使用由另一个进程。的
据推测,问题是,日志文件没有正确关闭时我关闭的StreamWriter。
有没有更好的方式来关闭的StreamWriter,以确保文件已打开,正确关闭?
更新:我已经解决了我的问题。它是由一个不相关的问题(其中一个单独的应用程序访问,我试图访问该文件)引起的。
我接受梅德Martovoi的回答,因为我认为这是谁在未来类似问题的其他人的最有用的;但一个重要的注意事项是确实需要的日志文件中的解决方案,以每次日志写入时间,这可能会导致不必要的开销被打开。
我总是在使用
语句包装这样的代码
使用(StreamWriter的作家= File.AppendText(路径))
{
writer.WriteLine(这);
writer.WriteLine(就是额外);
writer.WriteLine(文字);
}
但的StreamWriter
关闭
方法一模一样的如的Dispose
。
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.
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
.
这篇关于的StreamWriter / StreamReader的文件在由另一个进程使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!