为什么 streamwriter 写入文件的一半而不是覆盖

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

这是我的原始文件

[
  {
    "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
  }
]

现在我想加载它的内容,删除一个项目,然后覆盖整个文件

// 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);
    }
}

jsonstreamWriter.Write(json)中的值为

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

所以它是有效的。

但由于某些原因,在执行 Write 之后一团糟

[
  {
    "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
  }
]

我怎样才能让我的 streamWriter 真正被覆盖,以及为什么当我打开新的 FileStream 时会发生这种情况? streamReader 不应该不知道之前的操作吗?我想这就是它不从索引 0 开始的原因。

或者可能有更简单的方法 read/write 从文件中获取锁(防止其他程序修改?)

听起来你需要使用 Truncate 作为文件模式,当你打开它进行覆盖时。