Saving and Retrieving richtextbox control’s content (.rtf file) in database
Let’s start with a very simple application.
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.
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.
rtfContent.Rtf = encoding.GetString(rtf, 0, Convert.ToInt32(bytesReceived));
Bye

This was originally posted here.
*This post is locked for comments