如何将“sql server Blob”字段“转换”为“常规”文件?

时间:2011-12-02 13:53:09

标签: sql-server blob

我有一个blob字段(我假设)一个PDF文件。 如何转换并获取真实文件?

1 个答案:

答案 0 :(得分:4)

刚从我之前使用过的代码中修改了这个,从代码注释判断它是从别人那里复制的,但我不知道在哪里。绝对有效,除非我把它搞砸了,试图让它变得通用!

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

}