0

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.

Lord Relix
  • 922
  • 5
  • 23
  • 50

2 Answers2

1

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);
Win
  • 61,100
  • 13
  • 102
  • 181
1

do you have to write the file to disk? It's easy enough to send an iText created pdf directly to email from this SO answer from Brianng

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);
Community
  • 1
  • 1
fnostro
  • 4,531
  • 1
  • 15
  • 23
  • This worked much better. No need to save to the folder and keep giving it maintenance by deleting files. Thanks a lot! – Lord Relix Apr 04 '14 at 19:42
  • 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" );_ – Vahid Jul 20 '17 at 05:46
  • 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. – fnostro Jul 20 '17 at 22:59