0

There are of course numerous questions similar to mine, but none really answer my problem or pose the question of why it works in debug and not in runtime.

I have made a FileSystemWatcher which waits for a file to be created in a directory on my server. Raises an Event and then picks up the file name that raised it copies it to another directory as a .csv. While debugging step by step everything works when i compile it breaks trying to 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);


    }
}   
Milos Grujic
  • 544
  • 6
  • 15

1 Answers1

1

The problem is that the FileSystemWatcher event fires when the file begins to be created. Try the following:

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;
    }

This function returns true if the file is being used. So you can do a loop like this

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

And wait to exit the loop to copy the file

taquion
  • 2,667
  • 2
  • 18
  • 29