我是新的c#,并正在编写一个程序,该程序将使用名为folderWatch的方法调用fileSystemWatcher来监视.xml文件的文件夹。 .xml文件包含一个电子邮件地址和一个图像的路径,一旦读取就会通过电子邮件发送。我的代码工作正常,如果我一次只添加几个XML,但是当我试图将大量数据转储到文件夹fileSystemWatcher不处理所有这些文件时。请帮助我指出正确的方向。FileSystemWatcher丢失文件
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);
}
}
机会是其缺少他们,因为花费的时间做所有的代码 - 它拧断,并有文件的队列 – BugFinder
您必须使用错误事件得到FSW告诉你,你做错了。 –
FSW非常容易出错。由于某些文件系统事件,它会随机停止监听 - 没有任何错误传送。如果有兴趣,我有一个[可观察FileSystemWatcher的(http://idcomlog.codeplex.com/SourceControl/latest#IdComLog.Reactive/FileSystem.cs),使得它更容易可靠地使用。 –