为什么我的流不可读? [英] Why is my Stream not Readable?
问题描述
这是我的问题的续集这里关于修剪掉一个日志文件中的fat。
This is a sequel to my question here about trimming the fat off a log file.
我有这样的代码:
private readonly FileStream _fileStream;
private readonly StreamWriter _streamWriter;
. . .
const int MAX_LINES_DESIRED = 1000;
string uriPath = GetExecutionFolder() + "\\Application.log";
string localPath = new Uri(uriPath).LocalPath;
if (!File.Exists(localPath))
{
File.Create(localPath);
}
_fileStream = File.OpenWrite(localPath);
// First, remove the earliest lines from the file if it's grown too much
StreamReader reader = new StreamReader(_fileStream);
. . .
最后一行显示失败:
Which fails on the last line shown with:
System.ArgumentException was unhandled
_HResult=-2147024809
_message=Stream was not readable.
为什么不可读?我想也许是因为这个文件是空的,但是我添加了一行,并且仍然得到相同的错误信息。
Why is it not readable? I thought maybe because the file was empty, but I added a line to it, and still get the same err msg.
推荐答案
File.OpenWrite
创建一个不可读的流。如果您要读取和写入流,您需要使用 File.Open(localPath,FileMode.Open,FileAccess.ReadWrite)
。
File.OpenWrite
creates a non-readable stream. If you're going to be reading and writing to the stream, you need to use File.Open(localPath, FileMode.Open, FileAccess.ReadWrite)
.
另外,你可以使用 FileMode.OpenOrCreate
,这样就不需要你的 File。存在
条件。
Additionally, you can just use FileMode.OpenOrCreate
, and that will remove the need for your File.Exists
conditional.
这篇关于为什么我的流不可读?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!