Как "преобразовать" поле BLOB-объекта sql server в "обычный" файл? - PullRequest
3 голосов
/ 02 декабря 2011

У меня есть поле BLOB-объекта с (я предполагаю) PDF-файлом. Как конвертировать и получить настоящий файл?

1 Ответ

4 голосов
/ 02 декабря 2011

Только что исправил это из кода, который я использовал ранее, судя по комментариям к коду, он скопирован у кого-то другого, но я не уверен, где. Определенно работает, если только я не испортил его, пытаясь сделать его универсальным!

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

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...