2009-06-30 102 views
2

我从一个返回二进制文件的ftp web请求中获得响应流。 我想将二进制数据转换为byte [],然后对该数组进行编码并将其作为Web服务响应发送。在web服务soap响应中发送二进制文件

Stream responseStream = webResponse.GetResponseStream(); 
byte[] byteToEncode= ReadFully(responseStream,1024); 
String str=Convert.ToBase64String(byteToEncode); 

我使用的功能我在网上找到的流转换为字节[]

/// <summary> 
/// Reads data from a stream until the end is reached. The 
/// data is returned as a byte array. An IOException is 
/// thrown if any of the underlying IO calls fail. 
/// </summary> 
/// <param name="stream">The stream to read data from</param> 
/// <param name="initialLength">The initial buffer length</param> 

public static byte[] ReadFully (Stream stream, int initialLength) 
{ 
    // If we've been passed an unhelpful initial length, just use 32K. 
    if (initialLength < 1) 
    { 
     initialLength = 32768; 
    } 

    byte[] buffer = new byte[initialLength]; 
    int read=0; 

    int chunk; 
    while ((chunk = stream.Read(buffer, read, buffer.Length-read)) > 0) 
    { 
     read += chunk; 

     // If we've reached the end of our buffer, check to see if there's 
     // any more information 

     if (read == buffer.Length) 
     { 
      int nextByte = stream.ReadByte(); 

      // End of stream? If so, we're done 

      if (nextByte==-1) 
      { 
       return buffer; 
      } 

      // Nope. Resize the buffer, put in the byte we've just 
      // read, and continue 
      byte[] newBuffer = new byte[buffer.Length*2]; 

      Array.Copy(buffer, newBuffer, buffer.Length); 
      newBuffer[read]=(byte)nextByte; 
      buffer = newBuffer; 
      read++; 
     } 
    } 
    // Buffer is now too big. Shrink it. 

    byte[] ret = new byte[read]; 
    Array.Copy(buffer, ret, read); 
    return ret; 
} 

但我得到一个异常说:

This stream does not support seek operations. 

我希望得到任何帮助。

感谢, 萨拉

回答

0

你可能需要重新编写的readFully功能,避免类似长度的属性,这就需要更多地了解流比,能够把全流仍未完全接收。