2017-07-22 56 views
0

我已經嘗試使用StreamReader和StreamWriter,但我想要更快的方式做到這一點。我認爲BinaryReader和BinaryWriter會幫助我。我想讀取包含數組的文件塊,但我不能做到這一點。我試過這個塊的代碼:如何在c#中使用binaryreader和binarywriter讀取和寫入數組中包含的數組?

// for writing to a file 
      byte[] bytes = { 1, 2, 5, 7 }; 
      string path = "H:\\test.txt"; 

      using (var stream = new FileStream(path, FileMode.Append)) 
      { 
       stream.Write(bytes, 0, bytes.Length); 
      } 

      FileStream streams = new FileStream("H:\\test.txt", FileMode.Open, FileAccess.Read); 

//for reading 
byte[] block = new byte[16]; 
int i = 0; 

while (streams.Read(block, 0, 16) > 0) 
{ 
Console.WriteLine(block[i]); 
i++; 
} 

但這不適用於我。我沒有得到文件中的實際答案。是否有任何特殊的方法來一次讀取文件中的完整數組。

我也看到這個Can a Byte[] Array be written to a file in C#?以及,但我沒有得到它,請幫助我。

+0

其他問題有描述方法'File.WriteAllBytes'答案。很容易猜到還有一個'File.ReadAllBytes'方法。 –

回答

0

試試這個:

using (var filestream = File.Open(@"H:\\testBinary.txt", FileMode.Open)) 
      using (var binaryStream = new BinaryReader(filestream)) 
      { 
       for (var i = 0; i < arraysize; i++) 
       { 
        Console.WriteLine(binaryStream.ReadInt32()); 
       } 
      } 
+0

然後如何寫入文件。@ Ugur –

+0

你應該先試試。順便說一下,它並不比這更難。 @DiwasPoudel –

相關問題