我有以下代码来监视传入文件的文件夹。文件夹收到文件后,程序会发送一封电子邮件以及文件的附件,在本例中为 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);
}
}
}
}
任何帮助将不胜感激。