Kishore Kumar
Kishore Kumar

Reputation: 12874

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.

Upvotes: 3

Views: 4191

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062770

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

Upvotes: 6

parapura rajkumar
parapura rajkumar

Reputation: 24403

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

Upvotes: 0

Related Questions