文件更改时的通知?

时间:2009-04-06 14:30:59

标签: c# file filesystemwatcher

是否有一些机制可以在光盘上修改文件时通知我(在C#中)?

4 个答案:

答案 0 :(得分:182)

您可以使用FileSystemWatcher类。

public void CreateFileWatcher(string path)
{
    // Create a new FileSystemWatcher and set its properties.
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = path;
    /* Watch for changes in LastAccess and LastWrite times, and 
       the renaming of files or directories. */
    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite 
       | NotifyFilters.FileName | NotifyFilters.DirectoryName;
    // Only watch text files.
    watcher.Filter = "*.txt";

    // Add event handlers.
    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.Created += new FileSystemEventHandler(OnChanged);
    watcher.Deleted += new FileSystemEventHandler(OnChanged);
    watcher.Renamed += new RenamedEventHandler(OnRenamed);

    // Begin watching.
    watcher.EnableRaisingEvents = true;
}

// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
    // Specify what is done when a file is changed, created, or deleted.
   Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
}

private static void OnRenamed(object source, RenamedEventArgs e)
{
    // Specify what is done when a file is renamed.
    Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}

答案 1 :(得分:59)

答案 2 :(得分:5)

使用FileSystemWatcher。您只能过滤修改事件。

答案 3 :(得分:-1)

文件更改时发送电子邮件...下面的代码

           FileInfo fi1 = new FileInfo(fileLocation);
           DateTime lastWritetoFile = DateTime.Parse(fi1.LastWriteTime.ToString()); // 10/04/2019 15:40:17

           //I'm Storing last change in DB
           DateTime lastFileChange = DateTime.Parse(lastChange); //10/04/2019 14:40:17


            if(fi1.Exists)
            {
                if (lastWritetoFile > lastFileChange)
                {
                    sendEmailAlertFileChanged(email);
                    UpdateDb(lastWritetoFile, ID);
                }
            }
            else
            {
                sendEmailAlertFileNotFound(email1);
            }


        private static void sendEmailAlertFileChanged(string email)
        {

            MailMessage mail = new MailMessage("email from...", "email to....");
            SmtpClient client = new SmtpClient();
            client.Port = 587;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = true;
            client.Credentials = new NetworkCredential("login to email...", "password to email");
            client.EnableSsl = true;
            client.Host = "smtp.gmail.com";
            mail.Subject = "this is my test subject";
            mail.Body = "this is my test body";
            client.Send(mail);
        }

如果您运行应用程序时遇到错误,请确保您对Google帐户的应用程序访问权限较弱,可以在此处找到它:

https://myaccount.google.com/lesssecureapps?utm_source=google-account&utm_medium=web