FileSystemWatcher Windows无法停止设备的“USB大容量存储设备”

时间:2017-05-15 19:43:52

标签: c#

我在C#中创建了一个服务,当USB驱动器插入计算机时,该服务将启动FileSystemWatcher

它跟踪创建的新目录和复制到USB驱动器的文件。它运行良好,唯一的问题是当您单击安全删除硬件和弹出媒体时,您会收到Windows无法停止设备'USB大容量存储设备'的消息。

当有人点击安全删除硬件并弹出媒体时,有没有办法可以停止FileSystemWatcher

代码:

namespace USB_Drive2
{
public class FileWatcher
{
    private string Directory { get; set; }
    private string Filter { get; set; }

    private string _fromDir;

    FileSystemWatcher fileW = new FileSystemWatcher();

    public FileWatcher()
    {

    }

    public FileWatcher(string directory, string filter, string serverDIR)
    {
        this._fromDir = serverDIR;
        this.Directory = directory;
        this.Filter = filter;
    }

    public void StartFileWatcher()
    {
        fileW.Filter = this.Filter;
        fileW.Path = this.Directory;
        fileW.EnableRaisingEvents = true;
        fileW.IncludeSubdirectories = true;

        fileW.Created += new FileSystemEventHandler(onChanged);
        fileW.Renamed += new RenamedEventHandler(onReNamed);
    }

    public void StopFileWatcher()
    {
        fileW.EnableRaisingEvents = false;
        fileW.Dispose();
    }

    private void onReNamed(object sender, RenamedEventArgs e)
    {
        //Specify what is done when a file is changed, created, or deleted
        Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
        //var USBW1 = new FileWatcher(e.FullPath, "*.*", "a");
        //USBW1.StartFileWatcher();
    }

    private void onChanged(object sender, FileSystemEventArgs e)
    {
        //throw new NotImplementedException();
        //string _combined;
        string _localCombined;
        string _timeOfDay;
        DateTime loacalDate = DateTime.Now;
        _timeOfDay = loacalDate.TimeOfDay.ToString();
        _timeOfDay = _timeOfDay.Replace(":", "");
        _timeOfDay = _timeOfDay.Replace(".", "");
        _timeOfDay = _timeOfDay.Remove(6);
        _localCombined = loacalDate.Year.ToString() + loacalDate.DayOfYear.ToString() + _timeOfDay;

        //************************************************************************************************
        FileInfo fi1 = new FileInfo(e.FullPath);

        if ((fi1.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
        {
            Console.WriteLine("Directory {0} Created on {1} {2}", e.FullPath, fi1.CreationTime.Date.ToShortDateString(), fi1.CreationTime.TimeOfDay.ToString());

        }
        else
        {
            Console.WriteLine("File {0} Created on {1} {2}", e.FullPath, fi1.CreationTime.Date.ToShortDateString(), fi1.CreationTime.TimeOfDay.ToString());
        }
        //************************************************************************************************

    }
}
}

0 个答案:

没有答案