2014-09-28 124 views
1

這是我的代碼。Byte by Byte反向文件讀取

 string FileName = @"File.txt";  

     if (File.Exists(FileName)) 
     { 
      FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read); 

      BinaryReader br = new BinaryReader(fs); 

      for (long i = fs.Length; i > 0; i--) 
      { 
       Console.Write(Convert.ToChar(br.Read())); 
      } 

     } 
     else 
     { 

但它仍然給我相同的輸出..它從頭到尾以正確的順序讀取文件。我希望它從頭到尾閱讀。

問題解決了 終極密碼

string FileName = @"File.txt"; 

     if (File.Exists(FileName)) 
     { 
      FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read); 
      int length = (int)fs.Length; 

      BinaryReader br = new BinaryReader(fs); 

      byte[] myArray = br.ReadBytes((int)fs.Length); 

      for (long i = myArray.Length - 1; i > 0; i--) 
      { 
       Console.Write(Convert.ToChar(myArray[i])); 
      } 
      Console.WriteLine(); 
     } 
     else 
     { 
      Console.WriteLine("File Not Exists"); 
     } 

回答

0

您需要使用的BinaryReader不同Read方法(Read(byte[]buffer, int index, int length))指定啓動要讀取索引和數據的長度。

for(long i = fs.Length; i > 0; i--) 
{ 
    byte[] buffer = new byte[1]; 
    br.Read(buffer, i, 1); 
    Console.Write(Convert.ToChar(buffer[0])); 
} 

編輯: 我的做法並不好,如果你想用戶Read(byte[], int, int)方法,你應該先閱讀整個文件,然後扭轉數組,@Crowcoder在他的方案中提到。

+0

如何處理緩衝區...它給我錯誤 – LeCdr 2014-09-28 11:50:12

-1

剛剛看過的所有流中的字節,即保存到一個字節的列表,並扭轉它,像這樣:

List<byte> data = new List<byte>(); 
for (int i = 0; i < br.BaseStream.Length; ++i) 
    data.Add(br.ReadByte()); 

data.Reverse(); 
0

使用的ReadBytes(fs.Length)來獲取一個字節數組,然後使用你的循環在陣列上。

+0

完美..解決了我的問題:D – LeCdr 2014-09-28 11:53:31

2

根據文件的大小,以下解決方案將消耗大量內存,因爲它將在內存中保存文件內容的兩個副本。但它應該是更小的文件(個人認爲比aprox的少大小10 MB。)OK,很容易理解:

// using System; 
// using System.IO; 

byte[] fileContents = File.ReadAllBytes(filePath); 
byte[] reversedFileContents = Array.Reverse(fileContents); 
… // process `reversedFileContents` instead of an input file stream 

PS:如果你要處理更大的文件(大小爲許多MB的那些),您不應該使用此解決方案,因爲它可能會很快導致OutOfMemoryException s。我建議你將合理大小(例如64KB)的文件塊讀入內存(從最後開始,然後開始執行搜索)並逐個處理這些文件。