a c# byte array from a binary sql field - GetBytes
Posted on 2004-09-30
I want to read some binary data I have in sql.
first I make a reader from a sproc call:
Cmd = new SqlCommand("sp_get_binary", SqlConn);
Cmd.CommandType = CommandType.StoredProcedure;
reader = Cmd.ExecuteReader();
what's returned is a reader of 1 field and 1 row. I can get the data like this:
while ( reader.Read() )
numBytes = reader.GetBytes(0, startIndex, byteArray, 0, bufferSize); // where startIndex=0 and bufferSize=100
now my the byte array "byteArray" is filled with stuff, but the wrong number of stuff. The GetBytes method uses the bufferSize, which must be assigned, to size the byte array returned.
What I want is the byte array sized to fit the returned value.
Question 1: Should I always set the buffer size of a GetBytes call to a value over the maximum possible return value? So like, should I set it to ten zillion if I think the returned array could be large?
The source below attempts to get a sized byte array:
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
while (numBytes == bufferSize)
startIndex += bufferSize;
numBytes = reader.GetBytes(1, startIndex, byteArray, 0, bufferSize);
bw.Write(keyBack, 0, (int)numBytesKey);
ms.Position = 0;
BinaryReader br = new BinaryReader(ms);
byteArray = br.ReadBytes( // why does this require a known length?
needless to say I don't know how to make this work exactly. What I need is a sized byte array from the DataReader, sized to the number of bytes returned by the db.
One of my biggest problems is I still don't completely "get" the how to use the various stream readers and writers to forge the structures I'm looking for. Why can't I easily get a sized byte array from a binaryreader? Is the MemoryStream object the fundamental stream holder for type conversions and such? Why am I running into many instances where I need to know the specific length of things I don't know the length of? Any resource links are greatly appreciated.