将.db文件转换为二进制。

9 浏览
0 Comments

将.db文件转换为二进制。

我正在尝试将一个.db文件转换为二进制文件,以便可以通过Web服务器进行流传输。我对C#还不太熟悉。我已经在网上找到了一些代码片段,但我不确定下面的代码是否把我引向了正确的方向。一旦我读取了数据,我该如何写入数据呢?BinaryReader会自动打开并读取整个文件,以便我可以直接以二进制格式写出吗?\n

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)); 
            }
        }
    }
}

\n编辑:用于流传输数据库的代码:\n

[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;
}

\n当我调用我的服务器时,没有返回任何内容。当我使用相同类型的方法来处理image/.png的内容类型时,它可以正常工作。

0
0 Comments

问题的出现原因:

这个问题的出现是因为原先的代码只是简单地将文件input.db复制到文件output.bin,使用File.Copy函数可以实现相同的功能。BinaryReader函数只是读取文件的所有字节,这是流式传输字节到期望二进制数据的输出流的合适开始。

解决方法:

一旦你有了与文件对应的字节,你可以像下面这样将它们写入Web服务器的响应:

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

另外,使用read1.ReadBytes(int.MaxValue)是一个危险的主意。可以考虑使用在.net 4.0中引入的Stream.Copy函数或分块复制的方法。已经更新了答案,展示了如何分块复制。

0