none
How to reuse Stream object? RRS feed

  • Question

  • Is there anyway to reuse Stream object? Instead of recreating new Stream i want to clear the existing data from the stream instance and use that instance for further logic

    public void Execute()
            {         
                using (Stream generatedXml = new VirtualStream())
                {
             
                    // this will populate the stream
                    this._mapper.Process(generatedXml);
    
                    AddProcessingInstruction(generatedXml);
                    
                    Converter.Convert(generatedXml);
                }
            }
          
            private void AddProcessingInstruction(Stream inputXml)
            {
                var absolutePath = System.Uri.EscapeUriString(new System.Uri("C:\\Test\Data\\StyleSheet.xsl").ToString());
                string piData = string.Format("type=\"text/xsl\" href=\"{0}\"", absolutePath);
                var processingInstruction = new XProcessingInstruction("xml-stylesheet", piData);
                var xDoc = XDocument.Load(inputXml);
                xDoc.AddFirst(processingInstruction);
    
                // How to empty the existing stream and reuse it?????
                inputXml = null;
    
                xDoc.Save(inputXml);
            }

    • Edited by lax4u Monday, November 19, 2012 11:31 PM
    Monday, November 19, 2012 11:30 PM

Answers

All replies

  • Clear the information and re-use the stream? How do you clear the information? It's only by calling dispose on stream, right? If you call Dispose, obviously you have to create new Stream, though the reference is same.

    Please mark this post as answer if it solved your problem. Happy Programming!

    Tuesday, November 20, 2012 3:51 AM
  • Well thats the question. How do we clear stream?
    Tuesday, November 20, 2012 3:34 PM
  • In general streams do not offer such functionality, the closest thing you to do is to set Position to 0 (assuming the stream supports seeking) and the write the data over the existing data (assuming the stream supports writing). This may work just fine if the new data length is larger or equal the old data length. If you write less data the stream will still contain old data at the end and you cannot truncate it.

    Tuesday, November 20, 2012 4:41 PM
    Moderator
  • What about

    Stream.SetLength(0);

    Will it work?

    Tuesday, November 20, 2012 4:46 PM
  • Right, forgot about that. It will work if the stream is seekable and writable.
    Tuesday, November 20, 2012 4:48 PM
    Moderator