| re: save BLOB to file from MySQL using c#
I did it with ByteFX drivers, because MySQLDriverCS has not defined
methods(like MySQLDataReader.GetBytes(...) )
Here is sample code-
--
string connectionString =
"Server=localhost;" +
"Database=iso_dokumentacia;" +
"User ID=;" +
"Password=;";
MySqlConnection cn = new MySqlConnection(connectionString);
FileStream fs; // Writes the BLOB to a file (*.jpg).
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.
cn.Open();
MySqlCommand logoCMD = new MySqlCommand("SELECT KapitolaBLOB FROM kapitola
WHERE ID_KAPITOLA=15",cn);
MySqlDataReader myReader =
logoCMD.ExecuteReader(CommandBehavior.SequentialAc cess);
while (myReader.Read())
{
// Get the publisher id, which must occur before getting the logo.
// Create a file to hold the output.
string dest = Server.MapPath("s.jpg");
fs = new FileStream(dest, 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.
//myReader.GetBytes(0, startIndex, outbyte, 0, bufferSize);
retval =(long) myReader.GetBytes(0, 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(0, startIndex, outbyte, 0, bufferSize);
}
// Write the remaining buffer.
bw.Write(outbyte, 0, (int)retval - 1);
bw.Flush();
// Close the output file.
bw.Close();
fs.Close();
}
myReader.Close();
cn.Close();
}
-- |