将流保存到文件



我正在写一个WCF服务来使用REST上传文件。

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

    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();
    }

在这种情况下,我无法获得文件流。长度,我有一个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:DropboxStuffRestServiceTrainingRestServiceTrainingUpload.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)

你有什么解决办法吗?

谢谢。

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

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

相关内容

  • 没有找到相关文章

最新更新