C# 使用filewatcher将文件发送到特定文件夹

C# 使用filewatcher将文件发送到特定文件夹,c#,winforms,C#,Winforms,只有组合框的窗体: 以及驱动器D中的MyTest文件夹,您可以在其中找到Folder1,Folder2,Folder3 我想查看文件夹MyTest中添加的.txt文件,如果在组合框a.s.o中选择了Folder1,则将其移动到Folder1 public void CreateFileWatcher(string path) { FileSystemWatcher fsw = new FileSystemWatcher("D:\\MyTest");

只有组合框的窗体:

以及驱动器D中的
MyTest
文件夹,您可以在其中找到
Folder1
Folder2
Folder3

我想查看文件夹
MyTest
中添加的
.txt
文件,如果在组合框a.s.o中选择了
Folder1
,则将其移动到
Folder1

 public void CreateFileWatcher(string path)
        {
        FileSystemWatcher fsw = new FileSystemWatcher("D:\\MyTest");

        fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
            | NotifyFilters.FileName | NotifyFilters.DirectoryName;

        fsw.Changed += new FileSystemEventHandler(OnChanged);

        fsw.Created += new FileSystemEventHandler(OnChanged);

        fsw.Deleted += new FileSystemEventHandler(OnChanged);

        fsw.Error += new ErrorEventHandler(OnError);

        fsw.EnableRaisingEvents = true;

    }

    private static void OnChanged(object source, FileSystemEventArgs e)
    {

    }

    private static void OnError(object source, ErrorEventArgs e)
    {

        Console.WriteLine("The FileSystemWatcher has detected an error");

        if (e.GetException().GetType() == typeof(InternalBufferOverflowException))
        {
           Console.WriteLine(("The file system watcher experienced an internal buffer overflow: " + e.GetException().Message));
        }
    }

这是您将文件移动为的方式

string sourceFile = @"C:\Users\Public\public\test.txt";
    string destinationFile = @"C:\Users\Public\private\test.txt";

    // To move a file or folder to a new location:
    System.IO.File.Move(sourceFile, destinationFile);

    // To move an entire directory. To programmatically modify or combine
    // path strings, use the System.IO.Path class.
    System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");
}

您可以执行
OnChanged
事件,如下所示:

private void OnChanged(object sender, FileSystemEventArgs e)
{
    string destFolder = Path.Combine(@"d:\", comboBox1.SelectedItem.ToString());
    if (!Directory.Exists(destFolder))
    {
        Directory.CreateDirectory(destFolder);
    }
    string destFileName = Path.Combine(destFolder, new FileInfo(e.FullPath).Name);
    try
    {
        File.Move(e.FullPath, destFileName);
    }
    catch (Exception ex)
    {
        Console.WriteLine("File move operation error:" + ex.Message);
    }
}

它可以工作,所以您遇到问题了吗?我不知道怎么做。我应该使用
File.Move
comboBox1.SelectedIndex
以某种方式吗?提示:检查
FileSystemEventArgs
的属性。另外,请阅读
File.Move
的文档。它用于物理地将文件从一个目录移动到另一个目录。组合框不是目录。我会编辑我的问题,因为我想人们不明白我的意思