1

Consider the following code:

internal class Program
{
    static async Task Main(string[] args)
    {
        var t = new Thing() { Name = "Some Long Name" };
        string path = @"c:\_Temporary\serialized.json";
        using var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
        await JsonSerializer.SerializeAsync(fs, t);
    }

    class Thing
    {
        public string Name { get; set; }
    }
}

When I run it, it creates a file with this content:

{"Name":"Some Long Name"}

Then if I change the object being serialized so that it will be a shorter file, e.g. by changing the Name property to something shorter:

var t = new Thing() { Name = "Short Name" }; // was "Some Long Name" before.

And re-run the code, the file now has this content:

{"Name":"Short Name"}me"}

Notice the invalid JSON at the end. It's clear the operation did not completely overwrite the file, but rather only overwrote enough of the file to apply the new content at the start of the file stream, leaving what was previously in the file intact.

This behavior was unexpected to me, and I don't know what I'm doing incorrectly -- is it with how I'm using FileStream (I tried different FileMode and FileAccess variations), or is it how I'm using JsonSerializer? Where does the problem lie? I know several ways I could fix this; I'm not asking "how do I make this code work correctly?". I simply would like to know where I went wrong.

1 Answer 1

1

This is how FileStream will work with FileMode.OpenOrCreate - it will write over the existing bytes of the file but will not truncate it (if new data is smaller than the original). You need FileMode.Create:

Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate.

Docs

1
  • Excellent, thank you!
    – rory.ap
    Commented Jul 6 at 20:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.