RoloffM
RoloffM

Reputation: 85

Converting string to System.IO.Stream

I have created a serializable class and added some objects. Now I want an xml file to be created (based on that class) when I click a button, so I did this:

private void Button1_Clicked(object sender, EventArgs e)
        {
            string fileName = "Data.xml";
            MySerializableClass msc = new MySerializableClass();
            XmlSerializer serializer = new XmlSerializer(typeof(MySerializableClass));
            StreamWriter sw = new StreamWriter(fileName, Encoding.UTF8); //'filename' is underlined
            serializer.Serialize(sw, msc);
            sw.Close(); //'Close' is underlined
            //'StreamWriter' does not contain a definition for 'Close' [...]
        }

Unfortunately I get the following error: cannot convert from 'String' to 'System.IO.Stream'. What does this mean? I don't get why encoding to UTF8 doesn't work. Using no encoding gives me the same error.

Upvotes: 0

Views: 13651

Answers (2)

Shane Ray
Shane Ray

Reputation: 1469

Please see the documentation for StreamWriter. https://msdn.microsoft.com/en-us/library/system.io.streamwriter(v=vs.110).aspx

Try this overload StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8);

Or you will need to create a Stream from the "data.xml" file, rather than just passing the filename.

Upvotes: 1

levent
levent

Reputation: 3644

streamwriter constructor parameters wrong ..

        string fileName = "your file path";
        using(FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate))
        {
            using (StreamWriter sw = new StreamWriter(fileStream, Encoding.UTF8))
            {
                MySerializableClass msc = new MySerializableClass();
                XmlSerializer serializer = new XmlSerializer(typeof(MySerializableClass));
                serializer.Serialize(sw, msc);
            }
        }

if you want to without FileStream, use this constructor.. StreamWriter(string path, bool append, Encoding encoding)

        string fileName = "your file path";
        using (StreamWriter sw = new StreamWriter(fileName, true, Encoding.UTF8))
        {
            MySerializableClass msc = new MySerializableClass();
            XmlSerializer serializer = new XmlSerializer(typeof(MySerializableClass));
            serializer.Serialize(sw, msc);
        }

Upvotes: 4

Related Questions