Сохранение потока в файл - PullRequest
2 голосов
/ 29 августа 2011

Я пишу службу 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();
    }

В этом случае я не смог получить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 Ответ

3 голосов
/ 29 августа 2011

Вы не можете прочитать размер потока, потому что он неизвестен (он даже может быть бесконечным). Вы должны прочитать все байты, пока вызов Readc не вернет больше никаких данных:

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

См. эту запись в блоге для подробного примера потоковой передачи.

...