该进程无法访问该文件,因为它正由另一个进程使用 - Filewatcher - C# - Console Application

MET*_*EAD 0 .net c# console-application file-watcher

我试图使用Filewatcher检测文件夹中的文件,并将文件移动到新位置.使用控制台应用程序这样做时,我收到错误The process cannot access the file because it is being used by another process.

File.Move(f.FullName, System.IO.Path.Combine(@"C:\Users\ADMIN\Downloads\FW_Dest", Path.GetFileName(f.FullName)));OnChanged方法中遇到此错误.请检查以下代码并帮助我解决此问题.提前致谢.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Security.Permissions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Run();

        }

        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]

        public static void Run()
        {


            FileSystemWatcher watcher = new FileSystemWatcher(); 
            watcher.Path = @"C:\Users\ADMIN\Downloads\FW_Source";
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Filter = "*.*";

            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.EnableRaisingEvents = true;

            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
        }


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

            DirectoryInfo directory = new DirectoryInfo(@"C:\Users\ADMIN\Downloads\FW_Source\");
            FileInfo[] files = directory.GetFiles("*.*");
            foreach (var f in files)
            {
                File.Move(f.FullName, System.IO.Path.Combine(@"C:\Users\ADMIN\Downloads\FW_Dest", Path.GetFileName(f.FullName)));
            }

        }


    }
}
Run Code Online (Sandbox Code Playgroud)

zmb*_*mbq 5

Changed正在更改文件时收到事件.您正在尝试在写入文件的进程完成之前移动它.一世

建议你首先尝试独占打开文件(拒绝读取,拒绝写入),并且只有当你成功关闭它并移动文件时.如果您没有成功,请等待几秒钟再试一次.