简体   繁体   English

将生成的文件保存到服务器

[英]Saving a generated file to the server

I am generating a PDF with the handy iText for C#. 我正在使用方便的iText for C#生成PDF。 Now, I basically just need to generate this PDF and e-mail it. 现在,我基本上只需要生成这个PDF并通过电子邮件发送它。 At the moment I can generate the file in PDF, but I don't want to hardcode a path to save the file. 目前我可以用PDF生成文件,但我不想硬编码保存文件的路径。 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. 谢谢你的帮助。

If you have HttpContext, you can use PhysicalApplicationPath . 如果您有HttpContext,则可以使用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 . 如果您没有HttpContext,则可以使用AppDomainAppPath

string filePath = string.Format("{0}App_Data\\ExportImport\\{1}",
   HttpRuntime.AppDomainAppPath, fileName);

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 很容易将iText创建的pdf直接发送到来自Brianng的这个SO答案的电子邮件

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM