【问题标题】:What should I use FileMode.Open or FileMode.Create for to make changes to a binary file我应该使用什么 FileMode.Open 或 FileMode.Create 来更改二进制文件
【发布时间】:2018-06-08 01:24:01
【问题描述】:

我正在使用 BinaryFormatter 和 FileStream 将复杂对象的列表写入二进制文件。对于写入文件的方法,我应该使用 FileMode.Create 创建一个新文件并用一个全新的文件覆盖它,还是应该做一些不同的事情来打开它并只更改已更改的内容?

我正在尝试序列化、反序列化、读取、写入以下内容:

List<Class> objectlist = new List<Class>();

【问题讨论】:

  • 将原始文件移动到备份并写入一个新文件。
  • 我将此列表用作我的主数据库,因此它会不断被读取和重写。
  • 仅修改部分文件并不是一个好方法。
  • 是的,如果您只想修改其中的一部分,那么编写一个全新的文件是低效的。
  • 通常将其缓存在内存中并根据需要将其读/写到文件中,但出于可靠性等考虑,您最终会得到一个符合 ACID 的数据库引擎。

标签: c#


【解决方案1】:

这两个功能应该可以解决您的问题。首先创建您的文件,然后读取它。

public void WriteToBinaryFormatterFile<T>(string filePath, T objectToWrite, bool append = false)
{
    using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        binaryFormatter.Serialize(stream, objectToWrite);
    }
 }

读取您的二进制格式化程序文件。

public T ReadFromBinaryFormatterFile<T>(string filePath)
{
    using (Stream stream = File.Open(filePath, FileMode.Open))
    {
        var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        return (T)binaryFormatter.Deserialize(stream);
    }
}

【讨论】:

  • 您确定这样附加到现有的序列化文件有效吗?即使是这样,您的 ReadFromBinaryFormatterFile 方法也只会读取流中的 first 对象,不是吗?
猜你喜欢
  • 1970-01-01
  • 2011-11-19
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-26
  • 2019-05-23
相关资源
最近更新 更多