簡體   English   中英

該進程無法訪問該文件,因為該文件正在被另一個進程使用-Filewatcher-C#-控制台應用程序

[英]The process cannot access the file because it is being used by another process - Filewatcher - C# - Console Application

我試圖使用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)));遇到此錯誤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)));
            }

        }


    }
}

Changed文件時,您將收到Changed事件。 您正在嘗試在寫入文件的過程完成之前移動它。 一世

建議您首先嘗試以獨占方式打開文件(拒絕讀取,拒絕寫入),並且僅在成功關閉文件並移動文件后才能打開。 如果未成功,請等待幾秒鍾,然后重試。

無需移動監視文件夾中的所有文件,只需移動創建的文件,如下所示:

private static void OnChanged(object source, FileSystemEventArgs e)
{
    File.Move(e.FullPath, Path.Combine(@"C:\Users\ADMIN\Downloads\FW_Dest", e.Name));
}

Thread.Sleep(2000)等待2秒更好的方法如下:

private static async void OnChanged(object source, FileSystemEventArgs e)
{
    await Task.Delay(TimeSpan.FromSeconds(2)).ConfigureAwait(false);

    File.Move(e.FullPath, Path.Combine(targetFolder, e.Name));
}

如果同時復制多個文件,這將防止程序鎖定多個線程。

我遇到了這個問題,將較大的文件移到了監視的文件夾中。

我在我的OnChange方法中調用了IsLocked方法,直到它返回false IsLocked經過它。

while (IsFileLocked(ImportFormat.FileName)) {
    //Do nothing until the file is finished writing
}

IsLocked方法:

/// <summary>
///     Tries to open the file for R/W to see if its lock. Returns Boolean
/// </summary>
/// <param name="filePath"></param>
/// <returns>bool</returns>
protected static bool IsFileLocked(string filePath) {
    FileStream stream = null;
    var file = new FileInfo(filePath);
    try {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }catch (IOException err) {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    } finally {
        stream?.Close();
    }

    //file is not locked
    return false;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM