hi
I have used the following code (mostly created by MSDN) to retrive a binary field from SQL database. it works but I have extra space between characters. for example if I save a text file with "Hello world" text, after retriving I have it like "H e l l o w o r l d". what is the problem??
I am really looking forward your answers
private void retrive()
{
publicvoid a(){
SqlConnection connection =newSqlConnection("Some Connection string");SqlCommand command =newSqlCommand("Select * from temp", connection);// Writes the BLOB to a fileFileStream stream;// Streams the BLOB to the FileStream object.BinaryWriter writer;// Size of the BLOB buffer.int bufferSize = 50;// The BLOB byte[] buffer to be filled by GetBytes.byte[] outByte =newbyte[bufferSize];// The bytes returned from GetBytes.long retval;// The starting position in the BLOB output.long startIndex = 0;// Open the connection and read data into the DataReader.connection.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess);while (reader.Read()){
// Create a file to hold the output.stream =
newFileStream("C:\\file.txt",FileMode.OpenOrCreate,FileAccess.Write);writer =
newBinaryWriter(stream);// Reset the starting byte for the new BLOB.startIndex = 0;
// Read bytes into outByte[] and retain the number of bytes returned.retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize);
// Continue while there are bytes beyond the size of the buffer.while (retval == bufferSize){
writer.Write(outByte);
writer.Flush();
// Reposition start index to end of last buffer and fill buffer.startIndex += bufferSize;
retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize);
}
// Write the remaining buffer.if (retval != 0)writer.Write(outByte, 0, (
int)retval - 1);writer.Flush();
// Close the output file.writer.Close();
stream.Close();
}
// Close the reader and the connection.reader.Close();
connection.Close();
}
}
Hi, I guess you're storing the text as NTEXT data type in your SQL Server. Since NTEXT/NVARCHAR/NCHAR data uses 2 bytes to stores a unicode character, when you retrieve the text from database using binary stream, each character is transferred as 2 bytes (with the 2nd byte empty), so that's why you found spaces between words. You?can?use?UltraEdit?to?open?the?generated?text?file?and?swith?to?hex?mode,?you'll?00s?between?normal?characters.
No comments:
Post a Comment