StreamWriter corrupting my RTF?
Basically, I want the user to fill out a form and have the RTF file updated with those values and then emailed as an attachment.
My code is as follows:
Code:
System.IO.StreamReader reader = new System.IO.StreamReader(Server.MapPath("~/GrantProposal/text2.rtf"));
string file = reader.ReadToEnd();
reader.Close();
file = file.Replace("gp1", frmDirector.Text);
file = file.Replace("gp2", frmPhone.Text);
System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("~/GrantProposal/text2.rtf"));
sw.Write(file);
sw.Flush();
sw.Close();
MailMessage mail = new MailMessage();
mail.To.Add(emailTo);
mail.From = new MailAddress(emailTo);
mail.Subject = "Grant Proposal";
//mail.Body = info;
Attachment attach = new Attachment(Server.MapPath("~/GrantProposal/text2.rtf"));
mail.Attachments.Add(attach);
SmtpClient smtpClient = new SmtpClient("localhost");
smtpClient.Send(mail);
When I test this, it emails the RTF fine, but when I download the attachment and try to open in Word, it gives me an error saying that the file is corrupted and data is either missing or invalid.
Any ideas?
I am using 3.5 if that helps..
Thanks
Re: StreamWriter corrupting my RTF?
First try to exclude these lines
Code:
file = file.Replace("gp1", frmDirector.Text);
file = file.Replace("gp2", frmPhone.Text);
You are changing the raw rtf directly and I'm not sure if there isn't a checksum in the rtf.
Re: StreamWriter corrupting my RTF?
Removing those lines didn't work. Even if I were to, how else would I be able to update the RTF with the user-inputted values?
It's something when I use sw.Write(file);
The file isn't corrupted if I comment that line out, but it also doesn't update.
Any other ideas?
Re: StreamWriter corrupting my RTF?
hah, just kidding..
I think the problem is when I'm reading the file to a string
string file = reader.ReadToEnd();
I get a bunch of characters in the string like "�" and there isn't even the "gp1" and "gp2" that I want to replace.
So I guess my question now is, how should I go about reading the RTF file to a string? I tried Encoding, but that didn't do anything..
Re: StreamWriter corrupting my RTF?
What about try to utilize RichTextBox class and it's LoadFile and SaveFile methods together with the Rtf property?
Something like:
Code:
RichTextBox rtb = new RichTextBox();
rtb.LoadFile(Server.MapPath("~/GrantProposal/text2.rtf"));
rt.Rtf = rt.Rtf.Replace("gp1", frmDirector.Text);
rt.Rtf = rt.Rtf.Replace("gp2", frmPhone.Text);
rtb.SaveFile(Server.MapPath("~/GrantProposal/text2.rtf"));
// ... you code follows