2013-03-22 94 views
2

我有這個c#程序,它是一個客戶端從服務器接收文件。有時它可以無縫工作。有時在fileName = Encoding.ASCII.GetString(dataByte, 4, fileNameLen);中有例外。c從一個系統到另一個系統的文件傳輸#

ArgumentOutOfRange Exception 
Index and count must refer to a location within the buffer. 
Parameter name: bytes 

如果fileNameLen值是812然後它工作正常。否則它將是1330795077。這是爲什麼?任何人都可以解釋我爲什麼這樣嗎?請。這是我的代碼。

 string fileName = string.Empty; 
     int thisRead = 0; 
     int blockSize = 1024; 
     Byte[] dataByte = new Byte[blockSize]; 
     lock (this) 
     { 
      string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\"; 
      ns.Read(dataByte, thisRead, blockSize); 
      int fileNameLen = BitConverter.ToInt32(dataByte, 0); 

      fileName = Encoding.ASCII.GetString(dataByte, 4, fileNameLen); 
      Stream fileStream = File.OpenWrite(folderPath + fileName); 
      fileStream.Write(dataByte, 4 + fileNameLen, (1024 - (4 + fileNameLen))); 
      while (true) 
      { 
       thisRead = ns.Read(dataByte, 0, blockSize); 
       fileStream.Write(dataByte, 0, thisRead); 
       if (thisRead == 0) 
        break; 
      } 
      fileStream.Close(); 
     } 

回答

3

指數和計數不表示以字節爲單位的有效範圍。

Encoding.ASCII.GetString()

ArgumentOutOfRangeException被拋出怎麼一回事,因爲對以下原因:

  • 索引或計數小於零。

  • 索引和計數不表示字節中的有效範圍。

計數是你的情況:fileNameLen

文檔狀態:

數據要轉換,例如從一個流中讀取數據,可以是僅 可用在順序塊。在這種情況下,或者如果 的數據量是如此之大,它需要被分成更小的塊,則 應用程序應使用Decoder或分別由 GetDecoder方法或GetEncoder方法,所提供的編碼器。

Documentation

2

您將需要檢查的dataByte內容時,它已經被轉移。如果你想創建和dataByte整數,你將它轉換爲的Int32在fileNameLen您可能會收到傻值像1330795077這是沒有有效的索引,在您的代碼ns.Read(dataByte, thisRead, blockSize);Encoding.ASCII.GetString(dataByte, 4, fileNameLen);

0

應該返回一個int值表示的實際長度讀。使用該返回值來控制要轉換爲字符串的字節數,以避免創建愚蠢的值。

相關問題