code to retrieve binary field from Sql Server

G

Guest

I have some code to read the contents of a varbinary(max) field in SQL Server
2005. It is working ok I just wanted to know if anyone had any comments on
it's efficiency.

Code to read from the field

using (SqlDataReader reader =
cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
if (reader.Read())
{
MemoryStream stream = new MemoryStream();
int bufferSize = 32768;
byte[] outbyte = new byte[bufferSize];
long startIndex = 0;
int columnIndex = 4;
int bufferIndex = 0;
int bytesReceived;
BinaryWriter bw = new BinaryWriter(stream);


while ((bytesReceived =
Convert.ToInt32(reader.GetBytes(columnIndex, startIndex, outbyte,
bufferIndex, bufferSize))) > 0)
{
bw.Write(outbyte, 0, bytesReceived);
bw.Flush();
startIndex += bufferSize;
}

cv.CVContent = stream;

return cv;

}



*********************************************

Code to write into the field

using (SqlCommand cmd = new SqlCommand())
{
int bufferSize = 32768;
Byte[] binaryDataBuffer = new Byte[bufferSize];
Byte[] binaryData = new Byte[inputStream.Length];
int bytesRead;

BinaryReader br = new BinaryReader(inputStream);
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);

while ((bytesRead = br.Read(binaryDataBuffer, 0,
bufferSize)) > 0)
{
bw.Write(binaryDataBuffer, 0, bytesRead);
}

binaryData = ms.ToArray();

cmd.Connection = gwenv.DatabaseConnection;
cmd.Parameters.Add("CVContent", SqlDbType.VarBinary).Value =
binaryData;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top