SQL Server VARBINARY(max) to c# byte[] -
i querying table (one of columns varbinary(max)
) returns records.
then save .dat.csv parse through .dat file , varbinary value string splitting file based on commas. need convert varbinary byte array. how can that?
good question. technically, can first converting character array, converting bytes. however, strings in .net unicode-encoded default (instead of ascii), gets tricky.
if @ possible, should try pull varbinary out of file byte array, using filestream you're reading instead of streamreader performs encoding conversions , file encoding type.
the problem byte-to-string-to-byte babelfishing bytecodes have special meaning in each unicode encoding, giving information decoder number of bytes should pull decode next character. when converting between various unicode encodings , .net-native utf-8 encoding strings, bytes gained, lost, , changed. when it's string, no biggie; encoding information stays string. when it's binary data, encoding , decoding can garble unless it's done in specific way.
the way work flawlessly if write file out using ascii encoding, read in such, cause each individual byte treated single character. can convert each char byte, , more significant byte of uint16 behind scenes of syetem.char, zero-padding byte fed in char, discarded.
var reader = new streamreader(new filestream("test.csv"), encoding.ascii); var varbinarystring = reader.read(<wherever varbinary in file/line>); var bytearray = varbinarystring.tochararray().select(c=>(byte)c).toarray();
technically, pull in using unicode encoding well, need know lot of specifics how wrote out bytes , how reader reading them in, can perform correct encoding , expansion (or deflation) necessary original bytestream.
edit: .net 2.0 version - no linq:
streamreader reader = new streamreader(new filestream("test.csv"), encoding.ascii); string varbinarystring = reader.read(<wherever varbinary in file/line>); char[] chararray = varbinarystring.tochararray(); byte[] bytearray = new byte[chararray.length]; for(int i=0; i< chararray.length; i++) { bytearray[i] = (byte)chararray[i]; }
Comments
Post a Comment