none
streamwriter and streamreader in c#

    Question

  • person operson1 = new person("my name", "my family");
                XmlSerializer xml1 = new XmlSerializer(typeof(person));
                StreamWriter writer1 = new StreamWriter("F:\\test.xml");
                try
                {
                    xml1.Serialize(riter1,operson1);
                }
                catch (Exception error)
                {
    
                    System.Console.WriteLine(error.Message);
                }
                finally
                {
                    if(writer1!=null){
                        writer1.Close();
                        writer1.Dispose();
    
                    }

    hi

    do i have to use open() and dispose() to this code?

    if yes what time i must use it ?

    What will help me ?

    • Edited by Arash_ Wednesday, April 5, 2017 1:27 PM
    Wednesday, April 5, 2017 1:15 PM

All replies

  • The StreamWriter class does not have an open method. Once created you just use its various Write... methods or, as you are doing, you can pass it to the XmlSerializer.

    The StreamWriter implements IDisposable therefore must be disposed after use. You can actually call Close or Dispose but don't need to do both because Close actually just calls Dispose anyway (see documentation).

    Wrapping your code in a try/finally is fine, but you can also use the 'using' statement to make your code a bit cleaner:

    using (StreamWriter writer = new streamWriter("F:\\test.xml"))
    {
       // use writer here...
    }
    

    At the end of the 'using' block, the object will be disposed for you automatically.

    • Proposed as answer by RohitArora Thursday, April 6, 2017 5:30 AM
    Wednesday, April 5, 2017 1:29 PM