2011-08-28 195 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