我是新的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),使得它更容易可靠地使用。 –