C# 从二进制文件中读取两个日期时出错

Jam*_*mie 3 c# date

从二进制文件中读取两个日期时,我看到以下错误:

“输出字符缓冲区太小,无法包含解码的字符,编码 'Unicode (UTF-8)' 回退 'System.Text.DecoderReplacementFallback'。参数名称:chars”

我的代码如下:

static DateTime[] ReadDates()
{
    System.IO.FileStream appData = new System.IO.FileStream(
       appDataFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);

    List<DateTime> result = new List<DateTime>();
    using (System.IO.BinaryReader br = new System.IO.BinaryReader(appData))
    {
        while (br.PeekChar() > 0)
        {
            result.Add(new DateTime(br.ReadInt64()));
        }
        br.Close();
    }
    return result.ToArray();
}

static void WriteDates(IEnumerable<DateTime> dates)
{
    System.IO.FileStream appData = new System.IO.FileStream(
       appDataFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);

    List<DateTime> result = new List<DateTime>();
    using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(appData))
    {
        foreach (DateTime date in dates)
            bw.Write(date.Ticks);
        bw.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

可能是什么原因?谢谢

Jon*_*eet 5

问题在于您正在使用PeekChar- 它试图解码二进制数据,就好像它是一个 UTF-8 字符一样。不幸的是,我看不到任何其他BinaryReader内容可以让您检测流的结尾。

可以继续调用ReadInt64直到它抛出一个EndOfStreamException,但这太可怕了。唔。您可以调用ReadBytes(8)然后BitConverter.ToInt64- 这将允许您在ReadBytes返回小于 8 个字节的字节数组时停止......虽然它不是很好。

顺便说一句,您不需要Close显式调用,因为您已经在使用using语句。(这对读者和作者都适用。)