Saving and Retrieving richtextbox control’s content (.rtf file) in database


Let’s start with a very simple application.

Form

Drop OpenFileDialog control in the application.

When user click on Pick File button using OpenFileDialog he will select a rtf file to display in richtextbox control.

The content of richtextbox control will be saved in the sql server table.

This is how our table looks like.

Table

File content is the image data type column where we will store our rtf content.

<!–[if gte vml 1]> <![endif]–>

Put the following code in Pick file button click.

if(openFileDialog1.ShowDialog() == DialogResult.OK)

{

try

{

rtfContent.LoadFile(openFileDialog1.FileName);

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

Put the following code in Save Button Click

SqlConnection conn=new SqlConnection(“Data Source=D-0824;Initial Catalog=WordInterOp; uid=sa;pwd=sa;”);

SqlCommand cmd=new SqlCommand();

cmd.CommandText = “Insert into RtfStore (fileName,fileContent) values ( @fname,@fcontent)”;

cmd.Connection=conn;

SqlParameter fileName=new SqlParameter(“@fname”,openFileDialog1.SafeFileName);

rtfContent.SaveFile(@”c:\temp.rtf”, RichTextBoxStreamType.RichText);

FileStream stream = new FileStream(@”c:\temp.rtf”, FileMode.Open, FileAccess.Read);

int size = Convert.ToInt32(stream.Length);

Byte[] rtf = new Byte[size];

stream.Read(rtf, 0, size);

SqlParameter fileContent=new SqlParameter();

fileContent.ParameterName=”@fcontent”;

fileContent.SqlDbType=SqlDbType.Image;

fileContent.Size=rtf.Length;

fileContent.Value=rtf;

cmd.Parameters.Add(fileName);

cmd.Parameters.Add(fileContent);

conn.Open();

int success=cmd.ExecuteNonQuery();

if(success==1)

{

MessageBox.Show(“Entered data successfully”);

}

openFileDialog1.SafeFileName- To get the name of file instead of the complete path.

rtfContent.SaveFile- Saving the content of the control in a rtf file.

RichTextBoxStreamType.RichText– This tells that we are saving richtext having some formatting and not just plain text.

Finally through filestream we are reading that file and saving it’s content in our sqlserver table.

Similary to read the rtf content from the database and display it in Richtextbox control, this is what we need to do

// cmd.commandText=”select fileContent from RtfStore where filename=’xyz’ “;

SqlDataReader dr =  cmd.ExecuteReader();

if (dr.Read())

{

Byte[] rtf = new Byte[Convert.ToInt32((dr.GetBytes(0, 0,

null, 0, Int32.MaxValue)))];

long bytesReceived = dr.GetBytes(0, 0, rtf, 0, rtf.Length);

ASCIIEncoding encoding = new ASCIIEncoding();

rtfContent.Rtf = encoding.GetString(rtf, 0, Convert.ToInt32(bytesReceived));

}

Bye

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

31 thoughts on “Saving and Retrieving richtextbox control’s content (.rtf file) in database”

  1. Excellent article 🙂 — One thing I noticed is that RTF format supports pictures in the document. I tested your code and worked well with text, however if you insert a picture in a RTF document and save it to the DB, then retreive it from the DB to display all the text is there but no picture…

    Have you encountered this is there a way around this?

    Like

  2. Hi All!

    Could be display it in Crystal Reports? In VS2008 Crystal Reports versions take it lika a Blob field :S Every one know how to fix it?

    Thx.

    Like

  3. Hi i want to get rtf document into Richtextbox with full formatting support … Is it possible????
    If possible please show me the code….Thanx in advance

    Like

    1. Hi Sandeep,
      The code that is here in this post – it was something that i tried 4-5 years back, at that time i did face issue of things not appearing with proper formatting. So it might not be possible.

      – Nishant Rana

      Like

  4. After going over a number of the articles on your website, I
    honestly appreciate your technique of writing a blog.
    I added it to my bookmark webpage list and will be
    checking back in the near future. Take a look at my
    web site as well and tell me what you think.

    Like

  5. Hello There. I found your weblog the usage of msn. This is an extremely smartly
    written article. I’ll make sure to bookmark it and return to read extra of your useful information. Thank you for the post.
    I will certainly comeback.

    Like

  6. I do not even know how I ended up here, but I thought this post was good.
    I do not know who you are but definitely you’re going to a famous blogger if you aren’t
    already 😉 Cheers!

    Like

  7. Hi! Do you know if they make any plugins to help with SEO?
    I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good results.
    If you know of any please share. Many thanks!

    Like

  8. I was recommended this website by my cousin. I’m not sure whether
    this post is written by him as nobody else know such detailed about my
    difficulty. You’re amazing! Thanks!

    Like

  9. You actually make it seem so easy with your presentation but I find this
    matter to be really something which I think I would never understand.
    It seems too complex and very broad for me. I’m looking forward for your next post, I will try to get
    the hang of it!

    Like

  10. With these changes, we want to give Annie’s lane opponents some more room to breathe against
    her early threat, but we’ve given Tibbers more late game playtime to
    compensate. Empowered Battle Roar heal changed to 20 +
    (10 x level) amplified by a 1% per 1% of Rengar’s missing health (from
    40 + (20 x level) health). Then climb to the second elevator and
    do ledge hangs all the way to the top.

    Like

  11. how do you resist those strong temptations to eat
    wrong foods and hurt your health and your light level.
    In principle you should always only buy the least processed rice.

    The more pronounced this process gets, the more serious the digestive issues
    grow into.

    Like

  12. First of all I want to say terrific blog! I had a quick question in which I’d
    like to ask if you do not mind. I was interested to find out how
    you center yourself and clear your mind prior to writing.
    I’ve had a tough time clearing my thoughts in getting
    my thoughts out. I truly do take pleasure in writing however it just seems like the
    first 10 to 15 minutes are usually lost simply just trying to
    figure out how to begin. Any recommendations or hints?
    Thank you!

    Like

  13. Very nice post. I simply stumbled upon your blog and wanted to
    say that I’ve truly enjoyed surfing around
    your weblog posts. In any case I’ll be subscribing for
    your feed and I hope you write once more soon!

    Like

  14. I’m really enjoying the theme/design of your site.

    Do you ever run into any browser compatibility issues?
    A number of my blog visitors have complained about my site
    not operating correctly in Explorer but looks great in Safari.
    Do you have any solutions to help fix this problem?

    Like

Please share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.