着信ファイルのフォルダーを監視する次のコードがあります。フォルダーがファイルを受信すると、プログラムはファイル (この場合は 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);
}
}
}
}
どんな助けでも大歓迎です。