Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Length of Stream object in WCF Client?

Tags:

c#

.net

stream

wcf

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.

like image 613
Kishore Kumar Avatar asked Feb 04 '26 13:02

Kishore Kumar


1 Answers

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).

like image 130
Marc Gravell Avatar answered Feb 06 '26 02:02

Marc Gravell