【问题标题】:MailMessage Delete attachments after sending if in Path.GetTempPath()MailMessage 在 Path.GetTempPath() 中发送后删除附件
【发布时间】:2017-12-23 12:02:00
【问题描述】:

请原谅我对 MailMessage 和 SmtpClient 类的陌生。我已经构建了一些基本可以使用的东西,但是在准备发送附件时,我有时会将附件复制到临时文件位置 (Path.GetTempPath() + @"\" + timestampWithFF),因为有时必须压缩它们才能发送。发生这种情况时,我想确保在发送后删除那里的文件(特别是因为那里的任何文件都会相对较大)。

两个问题: 1.我应该不用清理文件因为操作系统(win7)会做得很好吗? 2. 如何获取client.SendCompleted中附件的硬盘位置?

client.SendCompleted += (s, e) =>
{
    client.Dispose();
    foreach(Attachment a in msg.Attachments)
    {
        // want to actually delete the file from the HDD if it's in Path.GetTempPath();
    }
    msg.Dispose();
};

我知道我可以使用 a.Dispose(),但我不知道它有什么作用...我怀疑它正在处理对象(msg.Dispose 无论如何都会接下来做),但会保留文件硬盘。

我必须单独发送附件的文件路径吗? client.SendCompleted() 行位于: sendMailAsync(SmtpClient client, MailMessage msg) 方法。我可以将其更改为: sendMailAsync(SmtpClient client, MailMessage msg, List<string> attachments) 并将其添加到SendCompleted(),但感觉有点笨拙:

string tempDir = Path.GetTempPath();
foreach(string f in attachments)
{
    if(f.Contains(tempDir))    // want to actually delete the file from the HDD if it's in Path.GetTempPath();
    {
        if (File.Exists(f)) { File.Delete(f); }
    }
}

【问题讨论】:

    标签: c# .net dispose smtpclient mailmessage


    【解决方案1】:
    1. 我是否应该不必费心清理文件,因为操作系统 (win7) 会做得很好?

    如果我是你,我仍然会删除临时文件,尽管操作系统会在认为必要时清理它

    1. 如何在 client.SendCompleted 中获取附件的硬盘位置?

    附件中的文件可以通过ContentStream检索。他们的类型是FileStream

    client.SendCompleted += (s, e) =>
    {
        client.Dispose();
        var fileattachments = msg.Attachments
                              .Select(x => x.ContentStream)
                              .OfType<FileStream>()
                              .Select(fs => fs.Name)
                              .ToArray();
    
        msg.Dispose();
    
        string tempPath = Path.GetTempPath();
        foreach (var attachment in fileattachments )
        {
            if(attachment.Contains(tempPath)
            {
                File.Delete(attachment);
            }
    
        }
    };
    

    注意:先处置msg对象,再进行删除

    【讨论】:

    • hmmm... 这看起来很接近正确,但我从 Select 中得到了零个元素。我认为它在 Select(fs =>fs.Name) 之后需要一个 .ToArray() (或类似的),因为否则文件附件直到 msg.Dispose 之后才会被评估,所以没有什么可以循环的。
    • 对不起,我的错。我想起了我在它上面工作的过去,完全想念.ToArray();。感谢您的编辑! :) 希望在添加ToArray后对你有用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 2023-03-16
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多