Stream.Length throws NotSupportedException

前端 未结 6 1871
予麋鹿
予麋鹿 2020-12-14 15:30

I am getting a error when attempting stream.Length on a Stream object sent into my WCF method.

Unhandled Exception!
 Error ID: 0
 Error Code: Unknown
 Is War         


        
6条回答
  •  [愿得一人]
    2020-12-14 15:51

    This is what I do:

        // Return the length of a stream that does not have a usable Length property
        public static long GetStreamLength(Stream stream)
        {
            long originalPosition = 0;
            long totalBytesRead = 0;
    
            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position = 0;
            }
    
            try
            {
                byte[] readBuffer = new byte[4096];
    
                int bytesRead;
    
                while ((bytesRead = stream.Read(readBuffer, 0, 4096)) > 0)
                {
                    totalBytesRead += bytesRead;
                }
    
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
    
            return totalBytesRead;
        }
    

提交回复
热议问题