我想要一个程序,该程序将不断监视文件夹中的文件,当文件出现在所述文件夹中时,程序应等待文件可访问,然后将所述文件移动到另一个文件夹。目前这些文件没有从文件夹“test”移动到“test2”。
我这样做是为了当我单击开始按钮时,表单被最小化并在后台运行,不断监视文件夹。
private void btstart_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = @"C:\test";
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Created += new FileSystemEventHandler(watcher_FileCreated);
            watcher.EnableRaisingEvents = true;
        }
        public static bool Ready(string filename)
        {
            try
            {
                using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
                    return inputStream.Length > 0;
            }
            catch (Exception)
            {
                return false;
            }
        }
        void watcher_FileCreated(object sender, FileSystemEventArgs e)
        {
            string path1 = @"C:\test";
            string path2 = @"C:\test2";
            string files = @"*.*"; 
            string[] fileList = Directory.GetFiles(path1, files);
            foreach (string file in fileList)
            {
                if (Ready(file) == true)
                {
                    File.Move(path1, path2);
                }
            }
        }
显然这并不明显,但发生的事情是文件没有从文件夹“test”移动到文件夹“test2”,没有抛出异常,没有错误,文件没有被任何东西使用,也不是打开,权限也都设置正确,文件很简单,没有被移动
编辑解决方案:由于此线程中发布的答案,代码现在可以工作。我自己添加了一些东西,以便处理重复的异常。
folderlocationpath & folderdestinationpath 变量通过文件夹浏览器对话框读取,以便用户可以自己选择 2 个文件夹位置这是我目前拥有的:
string path1 = folderlocationpath;
            string path2 = folderdestinationpath;
            string files = @"*.*";
            string[] fileList = Directory.GetFiles(path1, files);
            foreach (string file in fileList)
            {
                if (Ready(file) == true)
                    try
                    {
                        File.Move(file, Path.Combine(path2, Path.GetFileName(file)));
                    }
                    catch (IOException) // for duplicate files an exception that deletes the file in destination folder and then moves the file from origin folder
                    {
                        string files2 = Path.GetFileName(file);
                        string[] fileList2 = Directory.GetFiles(path2, files2);
                        foreach (string file2 in fileList2)
                            File.Delete(file2);
                        File.Move(file, Path.Combine(path2, Path.GetFileName(file)));
                    }
            }