简体   繁体   中英

Find Length of Stream object in WCF Client?

I have a WCF Service, which uploads the document using Stream class.

Now after this, i want to get the Size of the document(Length of Stream), to update the fileAttribute for FileSize.

But doing this, the WCF throws an exception saying

Document Upload Exception: System.NotSupportedException: Specified method is not supported.
   at System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream.get_Length()
   at eDMRMService.DocumentHandling.UploadDocument(UploadDocumentRequest request)

Can anyone help me in solving this.

Now after this, i want to get the Size of the document(Length of Stream), to update the fileAttribute for FileSize.

No, don't do that. If you are writing a file, then just write the file . At the simplest:

using(var file = File.Create(path)) {
    source.CopyTo(file);
}

or before 4.0:

using(var file = File.Create(path)) {
    byte[] buffer = new byte[8192];
    int read;
    while((read = source.Read(buffer, 0, buffer.Length)) > 0) {
        file.Write(buffer, 0, read);
    }
}

(which does not need to know the length in advance)

Note that some WCF options (full message security etc) require the entire message to be validated before processing, so can never truly stream, so: if the size is huge, I suggest you instead use an API where the client splits it and sends it in pieces (which you then reassemble at the server).

If the stream doesn't support seeking you cannot find its length using Stream.Length

The alternative is to copy the stream to a byte array and find its cumulative length. This involves processing the whole stream first , if you don't want this, you should add a stream length parameter to your WCF service interface

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM