2011-08-28 189 views
2

我正在使用REST编写WCF服务来上传文件。将流保存到文件

但我probleme来自这个代码:

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) 

您有任何解决方案吗?

谢谢。

回答

3

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

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

关于流媒体的广泛样本见this blog entry

+0

谢谢月 我试图在博客的代码,但是有一些错误: System.IO.IOException是由用户代码 消息未处理=该进程无法访问文件“C:\文件上传\电台.txt',因为它正在被另一个进程使用。 –

+0

它很好用,我只是忘记删除旧的代码,以前打开同一个文件。 但是当我尝试上传某个文件时,我仍然遇到另一个问题:“远程服务器返回错误:(400)错误的请求。”作为来自HttpRequest的服务,我曾经称之为操作。 –

+0

400是一个非常普遍的错误。也许你会在事件日志或IIS日志中找到更多信息。快速谷歌搜索显示了这个有前途的链接:http://talentedmonkeys.wordpress.com/2010/11/29/wcf-400-bad-request-while-streaming-large-files-through-iis/ – Jan