Wcf 将流保存到文件
我正在编写一个WCF服务来使用REST上传文件 但我的问题来自以下代码:Wcf 将流保存到文件,wcf,stream,bytearray,filestream,Wcf,Stream,Bytearray,Filestream,我正在编写一个WCF服务来使用REST上传文件 但我的问题来自以下代码: public void UploadFile(Stream fileStream, string fileName) { FileStream fileToupload = new FileStream("C:\\FileUpload\\" + fileName, FileMode.Create); byte[] bytearray = new byte[fileStrea
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)
你有什么解决办法吗
谢谢。您无法读取流的大小,因为它未知(甚至可能是无限的)。 您必须读取所有字节,直到Readc调用不再返回任何数据:
int count;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
....
}
有关流媒体的详细示例,请参阅。谢谢Jan。我在博客中尝试了该代码,但在中出现了一些错误:System.IO.IOException未通过用户代码消息处理=进程无法访问文件“C:\FileUpload\radio.txt”,因为它正被另一个进程使用。这很好,我只是忘记删除以前打开同一文件的旧代码。但是,当我试图上传我的一些文件时,我仍然有另一个问题:“远程服务器返回了一个错误:(400)错误请求。”作为对HttpRequest所提供服务的重复,我曾经调用该操作。400是一个非常普遍的错误。也许您可以在事件日志或IIS日志中找到更多信息。快速的谷歌搜索显示了这个有希望的链接: