【问题标题】:Convert .db to binary将 .db 转换为二进制
【发布时间】:2012-08-04 17:44:44
【问题描述】:

我正在尝试将 .db 文件转换为二进制文件,以便可以将其流式传输到 Web 服务器。我对 C# 很陌生。我已经在网上查看了代码 sn-ps,但我不确定下面的代码是否让我走上了正确的轨道。读取数据后如何写入数据? BinaryReader 是否会自动打开并读取整个文件,以便我可以将其以二进制格式写出来?

class Program
{
    static void Main(string[] args)
    {
        using (FileStream fs = new FileStream("output.bin", FileMode.Create))
        {
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                long totalBytes = new System.IO.FileInfo("input.db").Length;
                byte[] buffer = null;

                BinaryReader binReader = new BinaryReader(File.Open("input.db", FileMode.Open)); 
            }
        }
    }
}

编辑:流式传输数据库的代码:

[WebGet(UriTemplate = "GetDatabase/{databaseName}")]
public Stream GetDatabase(string databaseName)
{
    string fileName = "\\\\computer\\" + databaseName + ".db";

    if (File.Exists(fileName))
    {
        FileStream stream = File.OpenRead(fileName);

        if (WebOperationContext.Current != null)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "binary/.bin";
        }

        return stream;
    }

    return null;
}

当我调用我的服务器时,我什么也得不到。当我对图像/.png 的内容类型使用相同类型的方法时,它工作正常。

【问题讨论】:

  • 转换为二进制是什么意思? input.db的格式是什么?
  • @Audrey .db 是我可以在 Sqlite Manager 中打开的格式。 sqlite 的数据库还有其他格式吗?我对这个领域很陌生。谢谢!
  • 您能解释一下您的最终目标是什么吗? SQLite 数据库本身就是二进制的。
  • @Audrey 我的最终目标是将 sqlite 数据库本身从服务器流式传输到设备。我添加了上面的代码。

标签: c#


【解决方案1】:

您发布的所有代码实际上都是将文件 input.db 复制到文件 output.bin 中。您可以使用 File.Copy 完成相同的操作。

BinaryReader 只会读入文件的所有字节。将字节流式传输到需要二进制数据的输出流是一个合适的开始。

一旦你有了与你的文件相对应的字节,你就可以像这样将它们写入网络服务器的响应中:

using (BinaryReader binReader = new BinaryReader(File.Open("input.db", 
                                                 FileMode.Open))) 
{
    byte[] bytes = binReader.ReadBytes(int.MaxValue); // See note below
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.Close();
    Response.End();
}

注意:代码 binReader.ReadBytes(int.MaxValue) 仅用于演示概念。不要在生产代码中使用它,因为加载大文件会很快导致 OutOfMemoryException。相反,您应该以块的形式读取文件,以块的形式写入响应流。

有关如何执行此操作的指导,请参阅此答案

https://stackoverflow.com/a/8613300/141172

【讨论】:

  • Eeeem,read1.ReadBytes(int.MaxValue) 是危险的想法。可以在 net 4.0 中使用 Stream.Copy new 还是卡住应对?
  • 是的,我知道。更新了答案以显示如何分块进行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-02
  • 1970-01-01
  • 2011-09-04
  • 2014-11-07
  • 1970-01-01
  • 2021-02-24
相关资源
最近更新 更多