I am generating a PDF with the handy iText for C#. Now, I basically just need to generate this PDF and e-mail it. At the moment I can generate the file in PDF, but I don't want to hardcode a path to save the file. Example, I am saving the file like this:
string file = "C:\\Receipts\" + ConfirmationNumber + ".pdf";
Now, hardcoding a path like that is completely against best practices. How can I save the file properly, following best practice? Maybe to a folder inside the project itself? Thanks for any help.
Solutions1
do you have to write the file to disk? It's easy enough to send an iText created pdf directly to email from this
var doc = new Document();
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
doc.Open();
doc.Add(new Paragraph("First Paragraph"));
doc.Add(new Paragraph("Second Paragraph"));
writer.CloseStream = false;
doc.Close();
memoryStream.Position = 0;
MailMessage mm = new MailMessage("username@gmail.com", "username@gmail.com")
{
Subject = "subject",
IsBodyHtml = true,
Body = "body"
};
mm.Attachments.Add(new Attachment(memoryStream, "filename.pdf"));
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
Credentials = new NetworkCredential("username@gmail.com", "password")
};
smtp.Send(mm);
Talk1:
This worked much better. No need to save to the folder and keep giving it maintenance by deleting files. Thanks a lot!
Talk2:
Hi, I am also in same situation. I have a crystal report. i want to generate pdf from crystal report and send mail. As now its generating pdf and saving in local machine. i want to save in a server folder. Is there any way to do this?? I am using the following code to generate the pdf. RPT.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, true, "Quotation Report 00" );
Talk3:
You would have to contact the authors of iText to see if they have any interface for Crystal Reports. My answer here was over 3 years ago and was actually a reference to another SO user.
Solutions2
If you have HttpContext, you can use PhysicalApplicationPath.
string filePath = string.Format("{0}\\App_Data\\ExportImport\\{1}",
HttpContext.Current.Request.PhysicalApplicationPath, fileName);
If you do not have HttpContext, you can use AppDomainAppPath.
string filePath = string.Format("{0}App_Data\\ExportImport\\{1}",
HttpRuntime.AppDomainAppPath, fileName);
Talk1:
Thanks. Will try this :)
Talk2:
Make sure the folder exists in your web application before saving the file.