0

我有以下代码来监视传入文件的文件夹。文件夹收到文件后,程序会发送一封电子邮件以及文件的附件,在本例中为 pdf。但是,有时我们会收到多个文件,它会发送多封具有相同 pdf 文件但文件名不同的电子邮件。我必须发布pdf文件吗?我以为我是用 pdfFile.Dispose() 和 mail.Dispose() 来做的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Mail;

namespace Email
{
class Program
{
    static string files;
    static void Main(string[] args)
    {
        fileWatcher();
    }

    private static void fileWatcher()
    {
        try
        {
            //Create a filesystemwatcher to monitor the path for documents.
            string path = @"\\server\folder\";
            FileSystemWatcher watcher = new FileSystemWatcher(path);

            //Watch for changes in the Last Access, Last Write times, renaming of files and directories.
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.FileName | NotifyFilters.LastWrite
                | NotifyFilters.DirectoryName | NotifyFilters.CreationTime;

            watcher.Filter = "FILE*";

            //Register a handler that gets called when a file is created.
            watcher.Created += new FileSystemEventHandler(watcher_Created);

            //Register a handler that gets called if the FileSystemWatcher need to report an error.
            watcher.Error += new ErrorEventHandler(watcher_Error);

            //Begin watching the path for budget documents/
            watcher.EnableRaisingEvents = true;

            Console.WriteLine("Monitoring incoming files for Budget documents.");
            Console.WriteLine("Please do not close.");
            Console.WriteLine("Press Enter to quit the program.");
            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught", e);
        }
    }


    //This method is called when a file is created.
    static void watcher_Created(object sender, FileSystemEventArgs e)
    {

        try
        {
            //Show that a file has been created
            WatcherChangeTypes changeTypes = e.ChangeType;
            Console.WriteLine("File {0} {1}", e.FullPath, changeTypes.ToString());
            String fileName = e.Name.ToString();
            sendMail(fileName);


            // throw new NotImplementedException();
        }
        catch (Exception exc)
        {
            Console.WriteLine("{0} Exception caught", exc);
        }
    }

    static void watcher_Error(object sender, ErrorEventArgs e)
    {
        Console.WriteLine("The file watcher has detected an error.");
        throw new NotImplementedException();
    }

    private static void sendMail(string fileName)
    {
        try
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("From@mail.com");
            mail.To.Add("Me@mail.com");

            string filesDirectory = @"\server\folder\";
            string searchForFile = "FILE*";
            string[] searchFiles = Directory.GetFiles(filesDirectory, searchForFile);

            foreach (string File in searchFiles)
                files = File;
            Attachment pdfFile = new Attachment(files);

            mail.Subject = "PDF Files " + fileName;
            mail.Body = "Attached is the pdf file " + fileName + ".";
            mail.Attachments.Add(pdfFile);

            SmtpClient client = new SmtpClient("SMTP.MAIL.COM");

             client.Send(mail);
           //To release files and enable accessing them after they are sent.
            pdfFile.Dispose();
            mail.Dispose();

        }
        catch (Exception e)
        {
            Console.WriteLine("{0} Exception caught", e);
        }
    }

}

}

任何帮助将不胜感激。

4

1 回答 1

2

您的代码旨在查找目录中的最后一个 pdf,并将其作为附件发送,并将新创建的 PDF 文件名作为电子邮件中的文件名。

这是由于这里的代码。

string[] searchFiles = Directory.GetFiles(filesDirectory, searchForFile);

foreach (string File in searchFiles)
      files = File;
Attachment pdfFile = new Attachment(files);

mail.Subject = "PDF Files " + fileName;

如果您仔细观察,您会注意到在您的 foreach 循环中,它正在循环目录中与您的过滤器匹配的所有文件,然后将变量文件设置为循环中的文件。循环完成后,您的 files 变量将是目录中的最后一个文件。

接下来,您将最后一个文件附加到电子邮件中,并将主题设置为作为参数传入的文件名。

您最好找到文件存在,然后将文件添加为附件,例如。

using (MailMessage mail = new MailMessage())
{
    mail.From = new MailAddress("From@mail.com");
    mail.To.Add("Me@mail.com");

    //format our file paths
    string filesDirectory = @"\server\folder\";
    string fileFullPath = Path.Combine(filesDirectory, fileName);

    //file doesnt exist so exit the method
    if (!File.Exists(fileFullPath))
        return;

    using (var pdfFile = new Attachment(fileFullPath))
    {
        mail.Subject = "PDF Files " + fileName;
        mail.Body = "Attached is the pdf file " + fileName + ".";
        mail.Attachments.Add(pdfFile);

        SmtpClient client = new SmtpClient("SMTP.MAIL.COM");

        client.Send(mail);
        //To release files and enable accessing them after they are sent.
    }
}

在上面的示例中(是的,我切换到 using 语句),但您会注意到我不再搜索整个目录,而只是检查创建的文件是否仍然存在。而不是循环所有文件,这只会传输新创建的文件。

让我知道事情的后续。

干杯

于 2013-09-17T22:19:37.820 回答