2016-11-24 675 views
-1

可能有一些明显的我在这里失踪,但我似乎无法设置我的FileStream读取编码。代码如下:C#FileStream读取设置编码

FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read); 
      using (fs) 
      { 

       byte[] buffer = new byte[chunk]; 
       fs.Seek(chunk, SeekOrigin.Begin); 
       int bytesRead = fs.Read(buffer, 0, chunk); 
       while (bytesRead > 0) 
       { 
        ProcessChunk(buffer, bytesRead, database, id); 
        bytesRead = fs.Read(buffer, 0, chunk); 
       } 

      } 
      fs.Close(); 

其中ProcessChunk将读取值保存到对象,然后将对象序列化为XML,但读取的字符显示为错误。编码需要是1250.我还没有看到将编码添加到FileStream的选项。我在这里错过了什么?

+0

尝试使用StreamWriter而不是FileStream – tym32167

+1

由于您正在读取* bytes *,因此没有编码。如果这些字节构成文本,则将这些字节转换为需要编码器的文本。代码或问题中没有任何文本处理的痕迹(除了“我在哪里指定编码器”),所以问题是:您是否需要编码器? –

回答

1

而不是FileStream,请使用StreamReader。它有几个constructors,它们允许你指定编码。例如:

StreamReader srAsciiFromFile = new StreamReader(file, System.Text.Encoding.ASCII); 

我也建议写它:

using (StreamReader fs = new StreamReader ...etc) 

,而不是声明使用外部变量;并且您不需要在使用外进行关闭,因为the Dispose will handle that

+0

如何使用Streamreader指定块大小?我需要它从文件中的指定起始位置开始,每次读取定义大小的块,这就是为什么我使用FileStream。 – Flopn

+0

StreamReader上有一个等效的“Read”方法https://msdn.microsoft.com/en-us/library/9kstw824(v=vs.110).aspx;它只是现在编码已解决,你有“字符”而不是“字节”。 – Richardissimo