【问题标题】:doing file.copy exception thrown cannot access file is being used, code works when debugging when compiled not [duplicate]正在使用抛出的file.copy异常无法访问文件,编译时代码在调试时有效[重复]
【发布时间】:2024-01-23 22:57:01
【问题描述】:

当然有很多类似于我的问题,但没有一个真正回答我的问题或提出为什么它在调试而不是运行时有效的问题。

我创建了一个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);


    }
}   

【问题讨论】:

    标签: c# file console copy-constructor


    【解决方案1】:

    问题是 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;
        }
    

    如果文件正在使用,此函数返回 true。所以你可以做一个这样的循环

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

    并等待退出循环复制文件

    【讨论】: