c# - streamreader 的基本流位置使用单声道

标签 c# linux mono streamreader

我正在尝试编写一些简单的代码来索引一些维基百科 xml 页面。我的想法是通过使用 streamreader 读取一个字符来获取每个字符的字节偏移量,然后从字节流中保存位置,以便稍后可以返回到该位置。

使用仅包含“感\na\nb”(8 字节)并在每个字符后换行的简短测试文件。然后我尝试在主函数中使用这段代码:

using System;
using System.IO;

namespace indexer

{
    class MainClass
    {
        public static void Main(string[] args)
        {
            StreamReader sr = new StreamReader (@"/home/chris/Documents/len.txt");

            Console.Out.WriteLine(" length of file is " + sr.BaseStream.Length + " bytes ");
            sr.Read (); // read first byte. 
            Console.Out.WriteLine(" current position is  " + sr.BaseStream.Position);

            sr.Close ();
        }
    }
}

这给出了输出:

length of file is 8 bytes 
current position is  8

位置应该是 3,因为它应该只读取第一个字符。如果我再次使用 sr.Read(),我会正确获取下一个字符,但位置仍然是 8。

我是不是误解了它应该如何工作,还是我发现了某种错误?

谢谢。

最佳答案

不,这不是错误。 StreamReader 使用一个 1 KB 的缓冲区,当您调用 StremReader.Read() 时,缓冲区会被填满。

您应该调用 Encoding.GetByteCount() 方法来获取正在读取的字符或字符串中的字节数。当前编码可以在 StreamReader.CurrentEncoding 中找到。

关于c# - streamreader 的基本流位置使用单声道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28657854/

相关文章:

c# - 打开 XML : Get absolute coordinates a child shape

c# - ValueType.ToString 和 ReferenceType.ToString 的区别

linux - 如何为世界地图创建不同的缩放级别

asp.net-mvc - ASP.net MVC 与 Mono 和 Nginx - 如何配置索引文件

asp.net-mvc - Linux Mono 上的 SparkView 引擎

Mono 3.2.x 上的 Razor 引擎,具有快速 CGI - 目标特定的 .net?

c# - C# 上的边缘检测

c# - 将 MVC 数据传递给 Knockout View 模型

linux - 如何访问 ExecStop 或 ExecPostStop 中服务的返回码?

linux - 我可以使用 curl real time 减去 sys 和 user 来获得总响应时间吗