我是C#的新手,正在编写一个程序,使用fileSystemWatcher监视包含.xml文件的文件夹,该方法被称为folderWatch。.xml文件包含电子邮件地址和图像路径,一旦读取,将通过电子邮件发送。如果我一次只添加几个xml,那么我拥有的代码就可以正常工作,但是当我尝试将大量xml丢入文件夹时,fileSystemWatcher无法处理所有xml。请帮助指点一下方向。
private System.IO.FileSystemWatcher m_Watcher;
public string folderMonitorPath = Properties.Settings.Default.monitorFolder;
public void folderWatch()
{
if(folderMonitorPath != "")
{
m_Watcher = new System.IO.FileSystemWatcher();
m_Watcher.Filter = "*.xml*";
m_Watcher.Path = folderMonitorPath;
m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
m_Watcher.Created += new FileSystemEventHandler(OnChanged);
m_Watcher.EnableRaisingEvents = true;
}
}
public void OnChanged(object sender, FileSystemEventArgs e)
{
displayText("File Added " + e.FullPath);
xmlRead(e.FullPath);
}
读取xml
public void xmlRead(string path)
{
XDocument document = XDocument.Load(path);
var photo_information = from r in document.Descendants("photo_information")
select new
{
user_data = r.Element("user_data").Value,
photos = r.Element("photos").Element("photo").Value,
};
foreach (var r in photo_information)
{
if (r.user_data != "")
{
var attachmentFilename = folderMonitorPath + @"\" + r.photos;
displayText("new user data " + r.user_data);
displayText("attemting to send mail");
sendemail(r.user_data, attachmentFilename);
}
else
{
displayText("no user data moving to next file");
}
}
发送邮件
public void sendemail(string email, string attachmentFilename)
{
//myTimer.Stop();
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient(smtpClient);
mail.From = new MailAddress(mailFrom);
mail.To.Add(email);
mail.Subject = "test";
mail.Body = "text";
SmtpServer.Port = smtpPort;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
// SmtpServer.UseDefaultCredentials = true;
if (attachmentFilename != null)
{
Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachmentFilename);
disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
disposition.FileName = Path.GetFileName(attachmentFilename);
disposition.Size = new FileInfo(attachmentFilename).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
mail.Attachments.Add(attachment);
}
try
{
SmtpServer.Send(mail);
displayText("mail sent");
}
catch (Exception ex)
{
displayText(ex.Message);
}
}