做 file.copy 抛出的异常无法访问正在使用的文件,代码在编译时调试时有效

doing file.copy exception thrown cannot access file is being used, code works when debugging when compiled not

当然有很多类似我的问题,但 none 真正回答了我的问题或提出了为什么它在调试而不是在运行时工作的问题。

我制作了一个 FileSystemWatcher 等待在我服务器上的目录中创建文件。 生成 Event,然后选取生成它的文件名,将其作为 .csv 复制到另一个目录。 在逐步调试时,当我编译时一切正常,但尝试 File.copy() 时它会中断。

class Program
{
    public static string AdresaEXD { get; set; }
    public static string AdresaCSV { get; set; }
    public static string IzvorniFajl { get; set; } //source file
    public static string KreiraniFajl { get; set; }// renamed file

    static void Main(string[] args)
    {
        GledanjeFoldera();/ watcher
    }

    static void GledanjeFoldera()
    {
        AdresaEXD = @"H:\CRT_FOR_FIS\EXD";
        AdresaCSV = @"H:\CRT_FOR_FIS\CSV";

        FileSystemWatcher CRT_gledaj = new FileSystemWatcher(AdresaEXD,"*.exd");

        // Making filters 

        CRT_gledaj.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName;

        // create event handler

        CRT_gledaj.Created += new FileSystemEventHandler(ObradaITransformacijaEXD);

        // starting to watch

        CRT_gledaj.EnableRaisingEvents = true;

        // loop

        Console.WriteLine("Ako zelite da prekinete program pritisnite \'q\'.");

        while (Console.ReadLine() != "q");


    }

    private static void ObradaITransformacijaEXD(object source, FileSystemEventArgs e) // 
    {

        // 
        string NoviFajl = e.Name.Remove(e.Name.Length-4,4)+".csv";// new file name

        // create paths
         IzvorniFajl = System.IO.Path.Combine(AdresaEXD, e.Name);
        KreiraniFajl = System.IO.Path.Combine(AdresaCSV, e.Name);


       // copy file to other destination and delete after 
        System.IO.File.Copy(IzvorniFajl, KreiraniFajl, true);
        System.IO.File.Delete(IzvorniFajl);


    }
}   

问题是 FileSystemWatcher 事件在开始创建文件时触发。尝试以下操作:

private static bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }

此函数 returns 如果文件正在使用则为真。所以你可以像这样循环

while (IsFileLocked(new FileInfo(eventArgs.FullPath))) { }

并等待退出循环复制文件