B. *_*non 5 c# file-io uri filestream streamreader
这是我在这里有关从日志文件中删除胖文件的问题的后遗症。
我有以下代码:
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);
. . .
Run Code Online (Sandbox Code Playgroud)
在显示的最后一行失败:
System.ArgumentException was unhandled
_HResult=-2147024809
_message=Stream was not readable.
Run Code Online (Sandbox Code Playgroud)
为什么不可读?我以为可能是因为文件为空,但是我向其中添加了一行,并且仍然得到相同的err msg。
File.OpenWrite创建一个不可读的流。如果您要对流进行读写,则需要使用File.Open(localPath, FileMode.Open, FileAccess.ReadWrite)。
此外,您可以只使用FileMode.OpenOrCreate,这将消除对File.Exists条件的需求。