gpt4 book ai didi

wcf - 将流保存到文件

转载 作者:行者123 更新时间:2023-12-04 06:16:07 26 4
gpt4 key购买 nike

我正在编写一个 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)

你有什么解决办法吗?

谢谢你。

最佳答案

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

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

this blog entry有关流媒体的广泛示例。

关于wcf - 将流保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7223650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com