Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 庞大的列表<;双倍>;保存在小文件中_C# - Fatal编程技术网

C# 庞大的列表<;双倍>;保存在小文件中

C# 庞大的列表<;双倍>;保存在小文件中,c#,C#,我正试图在一个文件中保存一个巨大的双打列表。现在看起来是这样的: try{ FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.OpenOrCreate); using(BinaryWriter binaryWriter = new BinaryWriter(fs)) { foreach (double value

我正试图在一个文件中保存一个巨大的双打列表。现在看起来是这样的:

try{
       FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.OpenOrCreate);                   
       using(BinaryWriter binaryWriter = new BinaryWriter(fs))
       {
             foreach (double value in bigData)
             {
                  binaryWriter.Write(value);
             }
             binaryWriter.Close();
        }
        fs.Close();
} catch(System.IO.FileNotFoundException)
{
    MessageBox.Show("Unexpected save error\n", "Save error!", MessageBoxButtons.OK);
}
bigData是一个列表
,在测试用例中,它包含200万个对象

保存的文件大约有15MB,我认为这对于二进制数据来说是相当多的。有人知道我怎样才能把它弄得更小吗


另外,请记住,我需要在保存后打开此文件,但这是通过另一种方法完成的。

使用Zip算法压缩文件,有很多免费的实现。其中之一(方便地作为NuGet包):

同一个库可用于打开该文件。

一个是双精度的,所以200万次8大约是16MB。看起来不错

保存的文件大约有15MB,我认为这对于二进制数据来说是相当多的

a是8字节的数据:

Double
值类型表示双精度64位数字

你有200万个,这意味着1600万字节。对我来说似乎是对的

也许你真的想要
float
值?这样可以节省一半的面积。。。当然,这是以精度和射程为代价的

压缩数据可能会有帮助,但可能没有——这取决于数据是否包含大量重复信息。您可能会发现压缩它会增加大小,而不是减少大小——这正是拥有那么多可能值的本质

如果不了解您的上下文,我们无法判断您是否真的拥有15MB的有用信息,或者是否存在自然冗余。

!请注意,根据数据的不同,您可能会得到非常好的压缩,并且您的文件大小可能只有几百K(您输入了相同的
double
200万次),或者您可能会得到一个比未压缩版本大的文件(双倍的值是一个好的随机数生成器的输出,它一次生成8个字节)。这两种极端情况都不太可能发生,您可能会得到某种形式的中间地带,它将减少几MB,但您应该意识到这种可能性

try
{
    using(FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.OpenOrCreate))
    using(GZipStream gz = new GZipStream(fs, CompressionMode.Compress))
    using(BinaryWriter binaryWriter = new BinaryWriter(gz))
    {
        foreach (double value in bigData)
        {
          binaryWriter.Write(value);
        }
    }
} catch(System.IO.FileNotFoundException)
{
    MessageBox.Show("Unexpected save error\n",
    "Save error!", MessageBoxButtons.OK);
}
当你阅读它时,你只需将模式设置为解压缩即可

    using(FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open))
    using(GZipStream gz = new GZipStream(fs, CompressionMode.Decompress))
    using(BinaryReader binaryReader = new BinaryReader(gz))
    {
        //(use the reader as normal here)
    }

您还应该将
fs
放在
using
语句中,如果您正在使用
using
语句,则不需要调用
.Close()

它是有用的数据。你的计算是对的。我犯了一个错误,这就是为什么我想对它进行压缩。@sebap123:我不是说数据点没有用,但你真的需要它们每值64位的信息吗?不要假设压缩会有帮助-取决于你使用的数据类型嗯,很可能不是。@JimMischel:我的错误-想到了BinaryFormatter。将删除它