【问题标题】:How to "convert" a sql server Blob field to a "regular" file?如何将 sql server Blob 字段“转换”为“常规”文件?
【发布时间】:2012-01-11 13:02:34
【问题描述】:

我有一个带有(我认为)PDF 文件的 blob 字段。 如何转换并获取真实文件?

【问题讨论】:

  • 以编程方式(如果是什么语言)还是仅通过工具?
  • 如果存在工具,欢迎您!

标签: sql-server blob


【解决方案1】:

刚刚从我以前使用过的代码中修改了这个,从代码 cmets 来看,它是从其他人那里复制的,但我不确定在哪里。绝对有效,除非我只是把它搞砸了,试图让它通用!

private void WriteFiles() 
{

    SqlCommand cmd = new SqlCommand("SELECT FileName, FileData FROM ImageFiles", _conn);

    FileStream fs;                          // Writes the BLOB to a file
    BinaryWriter bw;                        // Streams the BLOB to the FileStream object.
    int bufferSize = 100;                   // Size of the BLOB buffer.
    byte[] outbyte = new byte[bufferSize];  // The BLOB byte[] buffer to be filled by GetBytes.
    long retval;                            // The bytes returned from GetBytes.
    long startIndex = 0;                    // The starting position in the BLOB output.

    // Open the connection and read data into the DataReader.
    _conn.Open();
    SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);

    if (!txtPath.Text.EndsWith("\\")) txtPath.Text += "\\";

    while (myReader.Read())
    {                
        // Create a file to hold the output.
        fs = new FileStream(txtPath.Text + myReader["FileName"].ToString().ToLower(),
                            FileMode.OpenOrCreate, FileAccess.Write);

        bw = new BinaryWriter(fs);

        // Reset the starting byte for the new BLOB.
        startIndex = 0;

        // Read the bytes into outbyte[] and retain the number of bytes returned.
        retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);

        // Continue reading and writing while there are bytes beyond the size of the buffer.
        while (retval == bufferSize)
        {
            bw.Write(outbyte);
            bw.Flush();

            // Reposition the start index to the end of the last buffer and fill the buffer.
            startIndex += bufferSize;
            retval = myReader.GetBytes(1, startIndex, outbyte, 0, bufferSize);
        }

        // Write the remaining buffer.
        bw.Write(outbyte, 0, (int)retval);
        bw.Flush();

        // Close the output file.
        bw.Close();
        fs.Close();
    }
    // Close the reader and the connection.
    myReader.Close();
    _conn.Close();

}

【讨论】:

    猜你喜欢
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    相关资源
    最近更新 更多