none
Serialize / deserialize / advantages and disadvantages Stream - FileStream RRS feed

  • Question

  • Hi,

    protected void SaveTraceXML<T>(string file, T dataObject)
    {
    	XmlSerializer serializer = new XmlSerializer(typeof(T));
    
    	using (Stream stream = new FileStream(file, FileMode.Create))
    	using (XmlWriter xmlWriter = XmlWriter.Create(stream, WriterSettingsExclusiv))
    	{
    		serializer.Serialize(xmlWriter, dataObject, Namespaces);
    	}
    }
    
    
    public static void WriteXml<T>(string filename, T template, XmlRootAttribute newRoot = null)
    {
    	lock (LockObj)
    	{
    		FileStream fs = new FileStream(filename, FileMode.Create );
    		XmlSerializer xs = new XmlSerializer(typeof(T), newRoot);
    		xs.Serialize(fs, template);
    		fs.Close();
    	}
    }

    What is the difference between FileStream and file? When should I use what and when?
    What are the advantages and disadvantages?
     
    With best regards Markus

    Wednesday, August 14, 2019 4:17 PM

Answers

  • Hi Markus,

    Thank you for posting here.

    First, you could look at File Class and FileStream Class.

    >>What is the difference between FileStream and file

    Second, there are the following difference:

    1. File is a static class and FileStream is a non-static class.

    2. File contains many functions including create, copy, delete, move, and open method and FileStream only could read and write the file. By the way, File also could contains the read and write method.

    3. File has some method that could return FilStream object. Such as the following code:

    FileStream fs = File.Open("d:\\test.txt", FileMode.OpenOrCreate);

    >>When should I use what and when?

    Third: As usual, File needs to be used when you use static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects.

    FileStream needs to be used when you provide a Stream for a file, supporting both synchronous and asynchronous read and write operations.

    >>What are the advantages and disadvantages?

    Last but not least, let me talk about it.

    File class is a static class, so it will occupy some memory when you used it. (disadvantages) However, it has many functions could do some operations on it(advantages).

    FileStream class is a non-static class, so it will occupy less memory than File(advantages). FileStream has a fewer functions.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Thursday, August 15, 2019 2:23 AM
    Moderator