使表单只包含一个组合框:enter image description here
驱动器D中的MyTest
文件夹,您可以在其中找到Folder1
,Folder2
,Folder3
enter image description here
如果在comboBox a.s.o中选择.txt
,我想在文件夹MyTest
中观看任何已添加的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));
}
}
答案 0 :(得分:2)
您可以实施以下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);
}
}
答案 1 :(得分:0)
这就是你将文件移动为
的方式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");
}