c# - Binary Writer/Reader extra character -
i converting legacy vb6 code c# , has me little baffled. vb6 code wrote data sequentially file. data 110 bytes. can read file fine in converted code, i'm having trouble when write file converted code.
here stripped down sample wrote real quick in linqpad:
void main() { int[,] data = new[,] { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }, { 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 } }; using ( memorystream stream = new memorystream() ) { using ( binarywriter writer = new binarywriter( stream, encoding.ascii, true ) ) { for( var = 0; < 2; i++ ) { byte[] name = encoding.ascii.getbytes( "blah" + i.tostring().padright( 30, ' ' ) ); writer.write( name ); for( var x = 0; x < 20; x++ ) { writer.write( data[i,x] ); } } } using ( binaryreader reader = new binaryreader( stream ) ) { // note +4 because of problem below. reader.basestream.seek( 30 + ( 20 * 4 ) + 4, seekorigin.begin ); string name = new string( reader.readchars(30) ); console.writeline( name ); // problem..this 4 bytes should not here. //reader.readint32(); for( var x = 0; x < 20; x++ ) { console.writeline( reader.readint32() ); } } } } as can see, have 30 character string written first. string never longer 30 characters , padded spaces if shorter. after that, twenty 32-bit integers written. 20 integers. know each character in string 1 byte. know 32 bit integer 4 bytes. in reader sample, should able seek 110 bytes ( 30 + (4 * 20) ), read 30 chars, , read 20 ints , that's data. however, reason, there 4 bytes being written after string.
am missing obvious (as case myself)? strings aren't null terminated in .net , 4 bytes anyway, not byte? 4 bytes coming from? i'm not directly calling write(string) can't prefixed length, it's not since it's after string. if uncomment readint32(), produces desired result.
the 4 bytes 4 characters you're writing. change string you're encoding ascii this:
("blah" + i.tostring()).padright(30, ' ') that is, pad string after you've concatenated prefix , integer.
Comments
Post a Comment