Cao Linh Truong
Cao Linh Truong

Reputation: 253

Load or convert varbinary from sql to textbox text?

I'm new one in C# programming.
At present I try to save and load a text file to sql server. I watched and searched some videos and document on youtube. They stored image file to sql. I try and already saved the text file to server (binary data). Now I stuck how to load or convert it:

When I save it, I used memorystream:

MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(textreview.Text);
byte[] theBytes = Encoding.UTF8.GetBytes(textreview.Text);
ms.Position = 0;
ms.Read(theBytes, 0, theBytes.Length);

//insert value to server
SqlCommand cmdb = new SqlCommand("insert into Assignment(text) values (@text)", con);
cmdb.Parameters.AddWithValue("@textname", textPathLabel.Text);
cmdb.Parameters.AddWithValue("@text", theBytes);

Now I try to load it but I stuck here!

//load from sql
byte[] picarr = (byte[])dr["text"];
ms = new MemoryStream(picarr);
ms.Seek(0, SeekOrigin.Begin);
StreamReader reader = new StreamReader(ms);
string text = reader.ReadToEnd();
textreview.Text = text;

Upvotes: 1

Views: 2666

Answers (1)

Filip Ekberg
Filip Ekberg

Reputation: 36327

Here's an example on how you convert a text to bytes and then back again:

var bytes = Encoding.UTF8.GetBytes("test");

This will give you a byte array that looks like this:

{ 116, 101, 115, 116 }

Now to get the text again, you can use Encoding.UTF8.GetString() like this:

Encoding.UTF8.GetString(bytes);

This means that you could simple do this when saving the value:

cmdb.Parameters.AddWithValue("@text", Encoding.UTF8.GetBytes(textreview.Text));

And then when loading it back you simply do this:

textreview.Text = Encoding.GetString((byte[])dr["text"]);

Upvotes: 4

Related Questions