filestream文件末尾的字符是什么?
我在while循环中搜索特定字符以检查它是否到达文件末尾。
哪个角色我可以搜索?
例如:
Indexof('/n') end of line Indexof(' ') end of word ???? ---------- end of file??
当Stream.Read返回零时,到达Stream的结尾。
来自MSDN, FileStream的示例:
// Open a stream and read it back. using (FileStream fs = File.OpenRead(path)) { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); while (fs.Read(b,0,b.Length) > 0) { Console.WriteLine(temp.GetString(b)); } }
要么,
using (StreamReader sr = File.OpenText(filepath)) { string line; while ((line = sr.ReadLine()) != null) { // Do something with line... lineCount++; } }
也许你正在寻找的是这个
using (StreamReader sr = new StreamReader("TestFile.txt")) { String line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } }
当FileStream返回0时,并不意味着您已到达文件末尾。 我有过这样的经历。
从MSDN:读入缓冲区的总字节数。 如果该字节数当前不可用 ,则可能小于请求的字节数,如果到达流的末尾,则可能小于零。
这种情况发生在像thumbdrive这样的慢速设备上。
没有EOF角色。 在循环中调用FileStream.Read
。 当.Read()
返回0表示没有读取字节时,就完成了。
文档对这种行为非常清楚。
http://msdn.microsoft.com/en-us/library/system.io.filestream.read.aspx
Read方法仅在到达流的末尾后才返回零。 否则,Read总是在返回之前从流中读取至少一个字节。 如果在调用Read时流中没有可用数据,则该方法将阻塞,直到可以返回至少一个字节的数据。 即使尚未到达流的末尾,实现也可以自由返回比请求更少的字节。
字符串(甚至文件中)没有“文件结束字符”。 字符串的长度是已知的( Length
属性),因此没有必要
阅读文件时,您可以检查:
- 如果
Stream.Read
返回0 - 如果
StreamReader.ReadLine
返回null
没有这样的角色。 如果调用FileStream.ReadByte,它将返回-1以获得文件结尾。 Read方法返回零字节读取。 如果在流周围使用StreamReader,则其ReadLine方法返回null或其EndOfStream属性返回true。
有时候你不想读全行。 例如,如果行很长,或者将字符串保存在临时变量中是没有用的。
在这些情况下,您可以在StreamReader上使用Peek()函数。 当它返回-1时,你就在最后。 例如:
// Reads a CSV file and prints it out line by line public static void ReadAndPrintCSV(string fullyQualifiedPath) { using (System.IO.StreamReader sr = File.OpenText(fullyQualifiedPath)) { string[] lineArray = null; while ((sr.Peek() > -1) && (lineArray = sr.ReadLine().Split(',')) != null) { foreach (string str in lineArray) { Console.Write(str + " "); } Console.WriteLine(); } } }