I am doing an app which inclueds richTextBox, for inserting text. I put some text into richTextBox and save it into my sql database (column is varbinary(MAX) data type, with this code:

byte[] myFile = Encoding.UTF8.GetBytes(richTextBox1.Text);

Here the text is changed into binary data, and them I add parameters and all whats needed, and finally:

cmd1.ExecuteNonQuery();

Then, when I want to open it, it opens in word (the code is made, that it opens in this program - depending on an extention and a file type).

So, when the Word is starting up, 1st it asks me if I want to change it (to use some other coding). I select nothing and click Ok. The text is there but it is not in the shape I inserted it into richTextBox. The font are all the same and are in Courier New (I didn`t save the the text in with this font, and even the text was not all the same).

Anyone has any clue how to get the same text out, as I saw inserted into richTextBox? Is this maybe anything to do with richTextBox, or this is only a matter of coding?

Are you first saving the encoded text as a Word document?
If so, are you using any Office Automation for this or just saving bytes?

Have you thought about saving it as XML, then loading it in WORD?

You can get the WORD XML tags by saving a simple document from WORD as XML -- then extract out all of the XML shell and plug your text inside.

I only save vbytes:

byte[] DobiDatoteko = File.ReadAllBytes(myFullPath);

Do you have any example of transforming the text (or bytes) into xml?

If you write the byte content of the RTF directly to disk (bypassing the SQL Server) and open it with word do you receive the same formatting message when opening the document? I suspect that you will. If you do this eliminates SQL as a culprit in this issue. It is probably Word complaining that you're asking it to open a non-native .docx file, or an RTF file it didn't create.

If you write the byte content of the RTF directly to disk (bypassing the SQL Server) and open it with word do you receive the same formatting message when opening the document? I suspect that you will. If you do this eliminates SQL as a culprit in this issue. It is probably Word complaining that you're asking it to open a non-native .docx file, or an RTF file it didn't create.

No. if I open it in the defualt program, or with word or with acrobat reader, the text IS the same as before.
I save it into the database with the :

byte[] DobiDatoteko = File.ReadAllBytes(myFullPath);

I open the file with:

byte[] buffer = (byte[])cmd1.ExecuteScalar();
                povezava.Close();
                FileStream fs = new FileStream(System.IO.Path.GetTempPath() + @"\MojaMapa\" + listView1.SelectedItems[0].Text, FileMode.Create); //, FileAccess.ReadWrite);
                fs.Write(buffer, 0, buffer.Length);
                fs.Close();

As said, this works without any problem.
But if I want to open it in a richTextbox with:

byte[] buffer = (byte[])cmd1.ExecuteScalar();
                String myString = Encoding.ASCII.GetString(buffer);

I got those strange signs.
Maybe I can not transform the bytes to string... there is maybe the wrong transformation.

Impossible. From your earlier code example you showed us this:

byte[] myFile = Encoding.UTF8.GetBytes(richTextBox1.Text);

richTextBox1.Text returns the unformatting string of words in the RTF textbox. Now richTextBox1.Rtf will give you the formatted rich text. It is impossible that you saw the formatted rich text using the code provided earlier, something else is wrong.

Now this is how you can save an RTF control to a file:

private void button2_Click(object sender, EventArgs e)
    {
      //This works OK
      const string fName = @"C:\rtf.rtf";
      if (System.IO.File.Exists(fName))
        System.IO.File.Delete(fName);
      System.IO.File.WriteAllBytes(fName, Encoding.UTF8.GetBytes(richTextBox1.Rtf));
      System.Diagnostics.Process.Start("wordpad", "\"" + fName + "\"");
    }

And using this SQL table:

IF OBJECT_ID('RTFStore', 'U') IS NOT NULL DROP TABLE RTFStore
Create Table RTFStore
(
  RecordId int identity(1000, 1) PRIMARY KEY,
  RTF varbinary(max)
)

You can store/retrieve RTF to a database using:

private void button3_Click(object sender, EventArgs e)
    {
      const string connStr = "Data Source=apex2006sql;Initial Catalog=Scott;Integrated Security=True;";
      int rtfRecordId;

      using (SqlConnection conn = new SqlConnection(connStr))
      {
        conn.Open();
        const string insQuery = "Insert Into RTFStore (RTF) Values (@RTF) Select CAST(SCOPE_IDENTITY() as int) As Result";
        using (SqlCommand cmd = new SqlCommand(insQuery, conn))
        {
          cmd.Parameters.Add(new SqlParameter("@RTF", SqlDbType.VarBinary)).Value = System.Text.ASCIIEncoding.UTF8.GetBytes(richTextBox1.Rtf);
          rtfRecordId = Convert.ToInt32(cmd.ExecuteScalar());
        }
      }
      using (SqlConnection conn = new SqlConnection(connStr))
      {
        conn.Open();
        const string selQuery = "Select RTF From RTFStore Where RecordId = @RecordId";
        using (SqlCommand cmd = new SqlCommand(selQuery, conn))
        {
          cmd.Parameters.Add(new SqlParameter("@RecordId", SqlDbType.Int)).Value = rtfRecordId;
          object oBuffer = cmd.ExecuteScalar();
          if (oBuffer != DBNull.Value)
          {
            byte[] buffer = (byte[])oBuffer;
            const string fName = @"C:\rtf2.rtf";
            File.WriteAllBytes(fName, buffer);
            System.Diagnostics.Process.Start("wordpad", "\"" + fName + "\"");
          }
        }
      }
    }

I'm not sure what is wrong with your original code since you haven't posted the complete sample but give this a shot.

commented: ice skating uphill with infinite patience and class :p +1

Impossible. From your earlier code example you showed us this:

byte[] myFile = Encoding.UTF8.GetBytes(richTextBox1.Text);

No. I do not get the text form richTextBox. I get the bytes from database and I would like to put this bytes (of course before thatr I have to transform them to string (text) into richTextBox.

Do we understand each other now?


This is now I get the bytes out of the database:

byte[] buffer = (byte[])cmd1.ExecuteScalar();

And this is how I transform bytes to string:

String myString = Encoding.ASCII.GetString(buffer);

And this is my problem - the transformation doesn`t work correctly. I o not get the correct text into "myString", but just some strange signs (as said earlier).
Here the richTextBox has nothing to do with this, richTextBox comes after that.

I would like to know how to do the correct transformtion from byte aray to string. This is my problem.


EDIT: I just did this code which should suppose to do the transformation:

byte[] buffer = (byte[])cmd1.ExecuteScalar();
                //String myString = Encoding.ASCII.GetString(buffer);
                System.Text.Encoding myEncoding = System.Text.Encoding.UTF8; //or .ASCII, or what ever I try here
                String myString = myEncoding.GetString(buffer);

But again no luck - the coding is incorrect.

That depends on how the data was originally stored in to the SQL Server. Are you putting the text there? If so please post the code.

1.
This is for the files from the hdd:

string myPath = treeView1.SelectedNode.FullPath;
                string myFileName = listView1.FocusedItem.Text;
                string myFullPath = Path.Combine(myPath, myFileName);
                byte[] DobiDatoteko = File.ReadAllBytes(myFullPath);

Is this OK?

2.
And this is how I save from a richTextBox - damn sorry you were right. Didnt even noticed that I save it this way. Iwill repair for the richTextBox.

byte[] saveText = Encoding.UTF8.GetBytes(richTextBox1.Text);

Upload your project man. You haven't been giving me complete answers for this whole thread :(

Where is the code that inserts the byte array in to the sql server? where is the code that writes the byte[] buffer to a file on the disk.

The point is only is saving text from richTextBox. And this is done here:

byte[] newText = Encoding.UTF8.GetBytes(richTextBox1.Rtf);

EDIT:

got it. Finaly. the problem was the when I want to show the text again in the richTextBox.

I had:

richTextBox1.Text = novoBesedilo.ToString();

I just changed it to:

richTextBox1.Rtf = novoBesedilo.ToString();

:) Thanks mate! You were in a huge help.
I Appreciate it.

No problem. I'm glad you got it working :)

Please mark this thread as solved if you have found an answer to your question and good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.