Search code examples
c#filefilestream

Why is streamwriter writting in the half of the file instead of overwriting


Here's my original file

[
  {
    "Quantity": 34,
    "ShopOrderId": "51e400ff-76b8-4be4-851a-86e2681db960",
    "Id": "ae7664cb-135e-4c01-b353-5ecf09ac56af",
    "Direction": 2
  },
  {
    "Accepted": true,
    "Id": "7bfc2163-2274-4a0e-83b9-203cb376a8f8",
    "Direction": 1
  }
]

Now I want to load its content, remove one item, and overwrite the whole file

// items loaded from file
var result = new List<QueueItem>();

using (var fs = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
{
    // reading from file
    using (var streamReader = new StreamReader(fs))
    {
        var json = streamReader.ReadToEnd();
        result = JsonConvert.DeserializeObject<List<QueueItem>>(json) ?? new List<QueueItem>();
    }
}

// removing unwanted items
result = result.Where(x => !IdsToRemove.Contains(x.Id)).ToList();

// overwriting whole file
using (var fs = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
    using (var streamWriter = new StreamWriter(fs))
    {
        var json = JsonConvert.SerializeObject(result, Formatting.Indented);
        streamWriter.Write(json);
    }
}

The value of json in streamWriter.Write(json) is

[
  {
    "Accepted": true,
    "Id": "7bfc2163-2274-4a0e-83b9-203cb376a8f8",
    "Direction": 1
  }
]

so it's valid.

But for some reason after performing Write it's a mess

[
  {
    "Accepted": true,
    "Id": "7bfc2163-2274-4a0e-83b9-203cb376a8f8",
    "Direction": 1
  }
]-135e-4c01-b353-5ecf09ac56af",
    "Direction": 2
  },
  {
    "Accepted": true,
    "Id": "7bfc2163-2274-4a0e-83b9-203cb376a8f8",
    "Direction": 1
  }
]

how can I make it that my streamWriter actually overwrite and also why does it happen when I'm opening new FileStream? shouldn't it be not aware of previous operations with streamReader? I guess it's the reason why it doesn't start from index 0.

Or maybe there is easier method to read/write from file while having locks (preventing other programs from modifying?)


Solution

  • Sounds like you need to use Truncate for the file mode when you open it to overwrite.