2011-10-12 36 views
1

我正在实现一个接受图像流的wcf服务。但是,当我运行它时,我正在得到一个异常。因为它试图在流完成之前获取流的长度。所以我想要做的是缓冲流直到它完成。但我找不到任何如何做到这一点的例子...如何缓冲输入流,直到它完成

任何人都可以帮忙吗?

到目前为止我的代码:

public String uploadUserImage(Stream stream) 
    { 
      Stream fs = stream; 

      BinaryReader br = new BinaryReader(fs); 

      Byte[] bytes = br.ReadBytes((Int32)fs.Length);// this causes exception 

      File.WriteAllBytes(filepath, bytes); 
    } 
+2

什么是异常的类型和消息? –

回答

5

,而不是试图取长,你应该从流中读取,直到它返回它的“完成”。在.NET 4中,这是很容易:

// Assuming we *really* want to read it into memory first... 
MemoryStream memoryStream = new MemoryStream(); 
stream.CopyTo(memoryStream); 
memoryStream.Position = 0; 
File.WriteAllBytes(filepath, memoryStream); 

在.NET 3.5没有CopyTo方法,但你可以写类似的东西自己:

public static void CopyStream(Stream input, Stream output) 
{ 
    byte[] buffer = new byte[8192]; 
    int bytesRead; 
    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     output.Write(buffer, 0, bytesRead); 
    } 
} 

不过,现在我们已经得到的东西来复制一个流,为什么麻烦先把它全部读入内存?我们只是把它写直到一个文件:

using (FileStream output = File.OpenWrite(filepath)) 
{ 
    CopyStream(stream, output); // Or stream.CopyTo(output); 
} 
+0

不断得到一个:在System.IO .__ Error.WinIOError(Int32 errorCode,字符串maybeFullPath)异常... – user808359

1

我不知道你正在返回什么(或不返回),但这样的事情可能会为你工作:

public String uploadUserImage(Stream stream) { 
    const int KB = 1024; 
    Byte[] bytes = new Byte[KB]; 
    StringBuilder sb = new StringBuilder(); 
    using (BinaryReader br = new BinaryReader(stream)) { 
    int len; 
    do { 
     len = br.Read(bytes, 0, KB); 
     string readData = Encoding.UTF8.GetString(bytes); 
     sb.Append(readData); 
    } while (len == KB); 
    } 
    //File.WriteAllBytes(filepath, bytes); 
    return sb.ToString(); 
} 

字符串可以我相信最高可达2 GB。

0

试试这个:

using (StreamWriter sw = File.CreateText(filepath)) 
    { 
     stream.CopyTo(sw); 
     sw.Close(); 
    } 
+0

为此工作,你将不得不确保源是在开始。 Stream.Seek()将帮助你。 –