我正在尝试将数据文件写入磁盘,这样我就可以缓存大量无法放入内存的数据。在一些早期测试中,我发现有时会写入数据,有时不会。下面是一个示例,它显示了该过程不起作用:
using System.IO;
using System;
namespace TestBinaryWriter
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
double dFoo = 1234.1234;
BinaryWriter bw = new BinaryWriter(File.OpenWrite("asdf"));
bw.Write(dFoo);
bw.Write(BitConverter.GetBytes(dFoo));
}
}
}'asdf‘文件的内容是空的,我不明白为什么。
发布于 2020-02-26 15:06:19
在using block中初始化和使用BinaryWriter:
using (BinaryWriter bw = new BinaryWriter(File.OpenWrite("asdf"))
{
bw.Write(dFoo);
bw.Write(BitConverter.GetBytes(dFoo));
}您的实现的错误是流没有关闭(通过调用close方法),并且内容没有正确地刷新到文件中。
使用using语句,它将自动导致Dispose方法被调用。在Dispose实现中,调用Close。这就是它的工作原理。
发布于 2020-02-26 15:13:16
BinaryWriter缓存数据,要将数据写入文件,it应显式执行此操作
...
bw.Write(dFoo);
bw.Flush(); // <- write all the data (dFoo) down
...或者是作者Close (Dispose)。典型的模式是using
{
...
// bw will be closed on leaving its scope
using BinaryWriter bw = new BinaryWriter(File.OpenWrite("asdf"));
bw.Write(dFoo);
bw.Write(BitConverter.GetBytes(dFoo));
...
} // bw will be closed here (with all data cached being written)或
using (BinaryWriter bw = new BinaryWriter(File.OpenWrite("asdf"))) {
bw.Write(dFoo);
bw.Write(BitConverter.GetBytes(dFoo));
} // bw will be closed here (with all data cached being written)发布于 2020-02-26 15:02:27
尝试将bw变量的声明和用法包含在using语句中,以便在退出程序之前自动清除(并因此清除)该变量。
https://stackoverflow.com/questions/60408376
复制相似问题