Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value cannot be null. Parameter name: stream while converting XmlDocument to stream

Tags:

c#

asp.net

I getting Argument Exception (Stream cannot be null) while calling Save method for XmlDocument.

Here is my sample code

    public Stream GetModifiedStream(Stream inputStream, string NewText)
    {
        Stream outputStream = null;
        try
        {
            XmlDocument document = new XmlDocument();
            document.Load(inputStream);
            XmlNode myNode = document.SelectSingleNode("/title");
            myNode.InnerText = NewText;
            document.Save(outputStream);
        }
        catch (Exception exp)
        {
            outputStream = inputStream;
        }
        return outputStream;
    }

My GetModifiedStream() method will take inputStream parameter and it will basically change the value of the node and convert XmlDocument to stream. and am getting exception while converting XmlDocument to stream

Can anyone tell me how to do this?

Thanks

like image 991
mathesh Avatar asked Dec 11 '25 19:12

mathesh


1 Answers

You have to use an existing stream for this, right now you pass null which causes the exception when being written to, instead i.e. use a MemoryStream:

public Stream GetModifiedStream(Stream inputStream, string NewText)
{
    Stream outputStream = new MemoryStream();
    try
    {
        XmlDocument document = new XmlDocument();
        document.Load(inputStream);
        XmlNode myNode = document.SelectSingleNode("/title");
        myNode.InnerText = NewText;
        document.Save(outputStream);
    }
    catch (Exception exp)
    {
        outputStream = inputStream;
    }
    return outputStream;
}

The type of stream you want to use (file stream, memory stream, network stream) really depends on your application, but you have to pass a valid stream instance to the XmlDocument.Save() method.

like image 115
BrokenGlass Avatar answered Dec 13 '25 07:12

BrokenGlass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!