.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Post New Web Links

dispose StreamReader causes ObjectDisposedException on stream, dot net 4.0

Posted By:      Posted Date: September 16, 2010    Points: 0   Category :.NET Framework
 
Hi, We have some code that populates a stringbuilder from a MemoryStream, using a StreamReader's ReadToEnd() method.  Platform is dot net 4.0 on Windows 7 machine, VS2010.  Sample code: using (StreamReader reader = new StreamReader(stream, true)) { builder.Append(reader.ReadToEnd()); } At the "}" I can quickwatch the stream and it looks fine.  I know the "using" causes dispose to be called on the streamreader at this point.  Stepping past the "}", quickwatch on stream shows "threw an exception of type 'System.ObjectDisposedException'" for the capacity, length and position properties of stream.  This is all enclosed in a "using MemoryStream" block.  Exiting the outer using block, I'll get an exception "Cannot access a closed stream."  Does anyone know a workaround.  If there is a more appropriate forum to post this question please advise.  Any help is greatly appreciated.  Thank you.


View Complete Post


More Related Resource Links

.NET Matters: Asynchronous Stream Processing

  

This month Stephen Toub discusses asynchronous stream processing.

Stephen Toub

MSDN Magazine March 2008


.NET Matters: Stream Pipeline

  

This month Stephen Toub explains how to make the most of dual processors when running encryption and compression tasks.

Stephen Toub

MSDN Magazine February 2008


Conversion of Byte Array to Memory stream

  

how to convert byte array to memory stream in vb.net.


Unable to read beyond the end of the stream in asp.net 2.0/C# web application

  

Hi All,

Thank you for advance.

I got the forllowing error in my asp.net 2.0/c# web application,


Message: Unable to read beyond the end of the stream.

Source: mscorlib

TargetSite: Void EndOfFile()

StackTrace:    at System.IO.__Error.EndOfFile()
   at System.IO.BinaryReader.ReadByte()
   at System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader)
   at System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader)
   at System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader)
   at System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader)
   at System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader)
   at System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader)
   at System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader)
   at System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader)
   at System.Web.UI.ObjectStateFormatter.DeserializeValue(SerializerBinaryReader reader)
 

File Stream Class

  
 I am trying to write to a text file while protecting it from concurrent access. What is the advantage of fileStream.lock ? (when I created a filestream in the code below, the file seemed to be protected from other processes using it). I am not sure if I need to use filestream.lock below. Please advise ..            Public Shared Sub writeToLogFile(ByVal logMessage As String)         Try             Dim strLogMessage As String = String.Empty             Dim strLogFile As String = System.Web.HttpContext.Current.Server.MapPath("~/Log.txt")             Dim swLog As StreamWriter             strLogMessage =  DateTime.Now.ToLongTimeString().ToString() & " ==> " & logMessage             Dim fileStream As New FileStream(strLogFile, FileMode.Append)            ' Lock all of the file after creating the filestream object             fileStream.Lock(0, fileStream.Length)      &nb

While dispose the com+, encounter error: failed due to the following error: Old format or invalid ty

  
I have web service to invoke com+ to do business layer checking. recently, the application encountered intermittently the following error while tried to dispose the com+ instance. Appreciate anyone who help for this. thanks!   System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to interface type 'System.IDisposable'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{805D7A98-D4AF-3F0F-967F-E5CF45312D2C}' failed due to the following error: Old format or invalid type library. (Exception from HRESULT: 0x80028019 (TYPE_E_UNSUPFORMAT)).   Server stack trace:    at System.IDisposable.Dispose()    at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)    at System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)    at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)   Exception rethrown at [0]:    at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage

stream live video into asp.net web page

  
 I need to stream a live video into a website I created in  visual web dvelpoer.  I thought I could  drag in a video control much in the same way as you would a image control but don't seem to have a video control. Any suggestions or ideas would be appreciated. Cheers 

InputStream.Read cannot read from stream

  
I am trying to read a file uploaded, parsing it to a byte array. But the problem is, it never gets read. When I debug it, the byte array will still have zero elements. int FileLength = File1.PostedFile.ContentLength; if (File1.PostedFile != null && File1.HasFile) { Stream fStream = File1.PostedFile.InputStream; byte[] contents = new byte[fStream.Length]; <strong>File1.PostedFile.InputStream.Read(contents, 0, FileLength);</strong> SPAttachmentCollection attachments = enquiry.Attachments; attachments.Add(fileName, contents); enquiry.Update(); } Problem occurs at the InputStream.Read. Afte that line, when i point to contents, it';s still zero. When I open the attachment in browser, it;s opened as a corrupt file or a red cross image.

Converting to stream after resize for SQL Insert

  
Hey guys,I'm running with this. Public Function ImageData(ByVal fu As FileUpload) As Byte() If fu.HasFile Then Dim imageBytes As Byte() = New Byte(fu.PostedFile.InputStream.Length) {} fu.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length) Return imageBytes Else Return Nothing End If End Function Public Function ImageResize(ByVal fu As FileUpload) As Bitmap Dim thumbWidth As Integer = 1024 Dim image As System.Drawing.Image = image.FromStream(fu.PostedFile.InputStream) 'Create a System.Drawing.Bitmap with the desired width and height of the thumbnail. Dim srcWidth As Integer = image.Width Dim srcHeight As Integer = image.Height Dim thumbHeight As Integer = (srcHeight / srcWidth) * thumbWidth Dim bmp As New Bitmap(thumbWidth, thumbHeight) 'Create a System.Drawing.Graphics object from the Bitmap which we will use to draw the high quality scaled image Dim gr As Graphics = Graphics.FromImage(bmp) 'Set the System.Drawing.Graphics object property SmoothingMode to HighQuality gr.SmoothingMode = Drawing2D.SmoothingMode.HighQuality 'Set the System.Drawing.Graphics object property CompositingQuality to HighQuality gr.CompositingQuality = Drawing2D.CompositingQuality.HighQu

Cannot read stream from uploaded file

  
I have a file upload which uploads a file and gets read into a byte array.int FileLength = File1.PostedFile.ContentLength; if (File1.PostedFile != null && File1.HasFile) { Stream fStream = File1.PostedFile.InputStream; byte[] contents = new byte[fStream.Length]; fStream.Read(contents, 0, (int)fStream.Length); fStream.Close(); fStream.Dispose(); The problem is, the fStream.Read seems to have a problem reading the stream. When I debug it, and the value of "contents" appears to be empty. The file gets uploaded as a corrupted file.  

StreamWriter Error: Cannot close stream until all bytes are written.

  
 Hi, I have a testing platform that allows data to be posted to a real time collection system.  It uses the StreamWriter object to send both HTTP and XML formats, It works fine, but there is a new request to submit uploaded files.  This again works fine, unless the files are over 70k (we need to test upto 3MB).  If it is over 70k, the response is the content-length too big.   I have changed it so that the content-length is now set dynamically, dependant on the size of the file uploaded.  However, when the StreamWriter.Close() runs, the execption The request was aborted: The request was canceled. is generated, with the InnerException Cannot close stream until all bytes are written.From what I have found on the web, the solution is use StreamWriter.Flush(), but this code is already in place. Code is as follows:  With WebRequest .Method = "POST" .ContentType = "application/x-www-form-urlencoded" .PreAuthenticate = False .AuthenticationLevel = Security.AuthenticationLevel.None End With If FileSize &gt; 0 Then WebRequest.ContentLength = FileSize End If Try RequestStream = WebRequest.GetRequestStream() StreamWriter = New StreamWriter(RequestStream) StreamWriter.Write(strDataToPost)

CA1063 : Microsoft.Design : Ensure that 'PageContentGrid.Dispose()' is declared as public and seal

  
OK... I'm getting my DB context like so: private ssCMSDataContext _dataContext; protected ssCMSDataContext DbContext { get { if (_dataContext == null) { _dataContext = new ssCMSDataContext(); } return _dataContext; } } public override void Dispose() { if (_dataContext != null) { _dataContext.Dispose(); } base.Dispose(); } When I run the code analysis I get the following warnings:  "CA1063 : Microsoft.Design : Ensure that 'PageContentGrid.Dispose()' is declared as public and sealed." "CA1063 : Microsoft.Design : Modify 'PageContentGrid.Dispose()' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns.  I don't understand what it wants me to do?  Little help....  

WebResponse Stream Terminating

  
Hi all, I'm making a request for a file via the HttpWebRequest object and then reading the stream from the HttpWebResponse.GetResponseStream() method. problem is, for text files (e.g. xml, html, etc.) the stream is fine, but if i'm getting binary files (images, media, etc.), the stream terminates prematurely (usually after 4 bytes or so). i'm using the following code: //---- declare vars Stream stream = response.GetResponseStream(); BinaryReader reader = new BinaryReader(stream); List<byte> buffer = new List<byte>(); int readByte; //---- read each byte, one by one into the byte buffer //while ((readByte = stream.ReadByte()) > 0) while ((readByte = reader.ReadByte()) > 0) { buffer.Add((byte)readByte); } //---- close the stream stream.Close(); //---- return the buffer as a byte array return buffer.ToArray(); Any ideas? i've used both Stream.ReadByte and also the BinaryReader.ReadByte, but they both terminate after four bytes, event though the response is much larger. if i make the request in the browser, the image/media pulls down just fine too.  

Dispose usage on managed resources

  
Hi,In my application i donot have/use unmamaged resources. is it necessary to implement dispose method ? Will not the GC clear it automatically ? if i have to use dispose what's benefit ?Vijaykishan | http://v2attechhorizon.blogspot.com

While trying to view a report in integrated mode i see an unsupported RPL stream error

  
Trying to deploy a report in integrated mode on MOSS 2007. SQL server version is 2008 R2. I see the following:   ??? ?????????? ? ????м???? ?? ??????? ????????? ??????. ?????????? ?????????????м?? ?????? ?????? RPL: 34.62.1836345404. ??????м?? ??????: 10.3.     Yes i know its in russian. Another fail of Microsoft not being able to see the error codes and strings in english language, makes finding solutions even harder, because first you must find HOW is this called in english, then look for solution. Okay so, i found out that it is actually transalted into: unsupported RPL stream version detected 34.62.1836345404 expected version 10.3 Now, everywhere around the webs they say that this is because my Add-in is out of date and i need new RS addin for MOSS 2007.  But the link is dead!    For example, here http://social.msdn.microsoft.com/Forums/en-US/sqlreportingservices/thread/61357765-52aa-4085-9ee0-4cb494a6c3ad   @For SQL 2008 R2 together with WSS 3.0 / MOSS 2007, you need the SQL server 2008 november CTP add in:  http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=44bda62c-0cda-4a99-8d0a-d7fe06b39422 But the link is dead and there is no hint as to what happened.   The only valid link i found is this: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=65606fdd-093f-4c
Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend