Search code examples
c#serializationoverwritefile-writing

Serialization is overwriting to the file


I created a class to create the process to read and write from the user. Could someone help me why it is writing to the text file but it is overwriting itself?

[Serializable]
class FileReadWrite<TFile>
{
    static Stream stream;
    static IFormatter formatter = new BinaryFormatter();

    //Writing to text file
    public static void SerializeData(List<TFile> objectToSerialize, string filePath)
    {            
        stream = new FileStream(filePath, FileMode.Create);        
        formatter.Serialize(stream, objectToSerialize);
        Console.WriteLine("Account Created SuccessFully!");
        stream.Close();
    }
}

Solution

  • Need FileMode.Append. As per the doc:

    Opens the file if it exists and seeks to the end of the file, or creates a new file. This requires Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception.

    So the solution will be:

    stream = new FileStream(filePath, FileMode.Append);
    

    Or you can have an explicit check like:

    if(!File.Exists(fileName))
    { // create a new file 
    }
    else //Append to a file