2014-12-27 4 views
0

한 번에 모두 읽는 대신에 먼저 파일을 열고 버퍼로 읽어 들인 다음 NetworkStream.write()을 호출하여 내용을 쓰려면 FileStream을 만듭니다.System.ArgumentException FileStream을 사용하여

다음은 코드입니다.

using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) 
{ 
    try 
    { 
     int len = (int)fs.Length; 
     byte[] data = new byte[len]; 
     byte[] buffer = new byte[bufferSize]; 
     int count, sum = 0; 
     while ((count = fs.Read(buffer, sum, len - sum)) > 0) 
     { 
      netstream.Write(buffer,sum,len-sum); 
      sum += count; 
     } 
... 

그것은 오류를 던지고 :

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

추가 정보 :

Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.

내가 여기 바운드 문제에서 어떤 배열을 볼 수 없습니다.

제안

을 기쁘게
+0

그것은 보인다 당신이'len' 바이트를'bufferSize' 크기의 버퍼로 읽는 것과 같습니다. 'len == fs.Length'와'bufferSize

+0

스트림에서'data' 변수로 읽거나 청크로 읽습니다. 버퍼로 덩어리로 데이터를 읽고 싶다고 잘못 생각하고 있다고 가정합니다. 'len-sum'은 스트림이 (len = fs.Length'와'sum = 0' 이후에) 즉시 모든 바이트를 읽도록합니다. –

+0

'buffer == len'을 현명하게 유지해야합니까? – Khan

답변

4

오프셋 및 길이가 버퍼 길이 없습니다 전체 파일을 기반으로해야합니다, 여기에 독서의 예는 FileStream에서 데이터를 차버 다른 스트림에 기입하다 :

 using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) 
     { 
       byte[] buffer = new byte[bufferSize]; 

       while (true) 
       { 
        var count = fs.Read(buffer, 0, buffer.Length); 
        if (count == 0) break; 
        netstream.Write(buffer, 0, count); 
       } 
     } 
관련 문제