Find the length of a Stream object in a WCF client?

I have a WCF service that loads a document using the Stream class.

Now after that I want to get the document size (stream length) in order to update the Attribute file for FileSize.

But by doing this, 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 resolving this issue.

+3
source share
2 answers

Now after that I want to get the document size (stream length) in order to update the Attribute file for FileSize.

No, do not do this. If you are writing a file, just write the file. With the simplest:

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

or up to 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 have to know the length in advance)

Please note that some WCF parameters (full message protection, etc.) require that the entire message be checked before processing, therefore it can never really transmit a stream, therefore: if the size is huge, I suggest you use the API instead where the client breaks it and sends it in parts (which you then collect on the server).

+6
source

If the stream does not support the search, you cannot find its length using Stream.Length

An alternative is to copy the stream to an array of bytes and search for its cumulative length. This includes first processing the entire stream, if you do not want it, you must add the stream length parameter to your WCF service interface

0
source

All Articles