2014-03-30 33 views
1

我有二进制文件BinaryFile读取为byte []

BinaryWriter binwriter = new BinaryWriter(File.Open("C:\\temp\\Users.bin", FileMode.Create)); 
binwriter.Write(buff); 
binwriter.Close(); 

它的工作原理,但我怎么可以从这个文件中读取数据? 我需要每次都读新行,而不是文件结尾。

BinaryReader binreader = new BinaryReader(File.Open("C:\\temp\\Users.bin", FileMode.Open)); 
byte[] m = binreader.ReadBytes(??????); //I to read only 1 line to m, and then I need to read again new line to m. 
+3

如果它是一个*二进制*文件,那么就没有“线”的概念。这是特定于*文本*。请提供更多信息。 –

+0

我写到文件数组像m,我想读取他们,我的意思是1阵列m – user3102962

+0

不,根本不清楚。你是什​​么意思的“文件阵列”?如果这是任意的二进制数据,那么你认为“线”是什么?例如,假设文件实际上包含一段以MP3编码的音乐 - 在这种情况下,“线”意味着什么?了解数据的性质并对其进行相应处理至关重要。 –

回答

0

二进制文件没有“线”的概念,但是你可以尝试做这样类似的文本文件阅读:

using (var streamReader = new StreamReader(filePath)) 
    { 
    string line; 
    while ((line = streamReader.ReadLine()) != null) 
    { 
     Console.WriteLine(line); 
    } 
    } 
0
using (StreamReader sr = new StreamReader(path)) 
      { 
       while (sr.Peek() >= 0) 
       { 
        Console.WriteLine(sr.ReadLine()); 
       } 
      } 

当然你也可以使其适应您的需求,而不是打印出来的控制台。

+1

为什么使用Peek?它更清洁(IMO),只是一次读取一行,直到“ReadLine”返回“null”。然而,所有这些都假设了一个文本文件,而这个问题似乎对数据是文本还是二进制数据感到困惑。 –

+0

是的,它确实令人困惑,但是因为他正在询问读一行代码,所以我认为他会以这种方式编写他的字节流。我建议使用Peek,因为它是在MSDN上建议的:http://msdn.microsoft.com/it-it/library/system.io.streamreader.readline.aspx。 –

+0

Ick - MSDN再次失败,IMO :( –