使用filewatcher将文件发送到特定文件夹
本文关键字:文件夹 filewatcher 文件 使用 | 更新日期: 2023-09-27 18:09:19
只有一个comboBox的表单:在这里输入图像描述
和D驱动器中的MyTest
文件夹,您可以找到Folder1
, Folder2
, Folder3
在这里输入图像描述
我想在文件夹MyTest
中观察任何添加的.txt
文件,如果在comboBox中选择了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));
}
}
您可以像下面这样实现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);
}
}
移动文件
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");
}