将流保存到文件

时间:2011-08-28 20:20:05

标签: wcf stream bytearray filestream

我正在使用REST编写WCF服务上传文件。

但我的问题来自这段代码:

    public void UploadFile(Stream fileStream, string fileName)
    {
        FileStream fileToupload = new FileStream("C:\\FileUpload\\" + fileName, FileMode.Create);

        byte[] bytearray = new byte[fileStream.Length];

        int bytesRead = 0;
        int totalBytesRead = 0;

        do
        {
            bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
            totalBytesRead += bytesRead;
        } while (bytesRead > 0);


        fileToupload.Write(bytearray, 0, bytearray.Length);
        fileToupload.Close();
        fileToupload.Dispose();
    }

在这种情况下,我无法获取fileStream.Length,并且我有一个NotSupportedException!

System.NotSupportedException was unhandled by user code
Message=Specified method is not supported.
Source=System.ServiceModel
StackTrace:
   at System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream.get_Length()
   at RestServiceTraining.Upload.UploadFile(Stream fileStream, String fileName) in D:\Dropbox\Stuff\RestServiceTraining\RestServiceTraining\Upload.cs:line 37
   at SyncInvokeUploadFile(Object , Object[] , Object[] )
   at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)

你有解决方法吗?

谢谢。

1 个答案:

答案 0 :(得分:3)

您无法读取流的大小,因为它的未知(甚至可能是无穷无尽的)。 您必须读取所有字节,直到Readc调用不再返回数据:

int count;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
    ....
}

有关流媒体的广泛示例,请参阅this blog entry