-1

I am trying to make a program for watching created and deleted files inside all USBs connected to a computer, my code is currently working well, until I copy a folder.

Example: I connect an USB drive I:/ . If I copy a file named file.mp4, its added to my db correctly. But if I copy it inside a folder as Movies/file.mp4, its not added the file either the folder.

What can be happening, or how can I get the file name even if it's inside a new folder??? I apreciate any suggestion.

enter image description here

Here is my Code:

   public void StartWatchers()
{
    ArrayList aFileWatcherInstance = new ArrayList();
    ArrayList lstFolders = new ArrayList();
    lstFolders.Add(@"I:/");
    lstFolders.Add(@"J:/");
    lstFolders.Add(@"K:/");
    lstFolders.Add(@"L:/");
    lstFolders.Add(@"M:/");
    lstFolders.Add(@"N:/");
    lstFolders.Add(@"O:/");
    lstFolders.Add(@"P:/");
    lstFolders.Add(@"Q:/");
    lstFolders.Add(@"R:/");
    lstFolders.Add(@"S:/");
    lstFolders.Add(@"T:/");
    lstFolders.Add(@"U:/");
    lstFolders.Add(@"V:/");
    foreach (string sMonitorFolder in lstFolders)
    {
        //Check if Directory Exisits
        if (Directory.Exists(sMonitorFolder))
        {
            FileSystemWatcher oFileWatcher = new FileSystemWatcher();
            oFileWatcher.InternalBufferSize = 65536;
            //Set the path that you want to monitor.
            oFileWatcher.Path = sMonitorFolder;
            oFileWatcher.Filter = "*.*";

            //Set the Filter Expression.


            oFileWatcher.Deleted +=  new System.IO.FileSystemEventHandler(FileSystemWatcherDeleted);
            oFileWatcher.Created +=  new System.IO.FileSystemEventHandler(FileSystemWatcherCreated);


            oFileWatcher.EnableRaisingEvents = true;

            oFileWatcher.IncludeSubdirectories = true;


            //Add a new instance of FileWatcher 
            aFileWatcherInstance.Add(oFileWatcher);
        }

    }

}


public static bool IsFileReady(string filename)
{
    // If the file can be opened for exclusive access it means that the file
    // is no longer locked by another process.
    try
    {
        using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
            return inputStream.Length > 0;
    }
    catch (Exception)
    {
        return false;
    }
}





void FileSystemWatcherCreated(object sender, System.IO.FileSystemEventArgs e)
{





    while (!IsFileReady(e.FullPath))
    {


    }

    if (IsFileReady(e.FullPath))
    {

        FileInfo fileInfo = new FileInfo(e.FullPath);
        String letra = e.FullPath.Substring(0, 3);


        if (connection.State != ConnectionState.Open)
            connection.Open();

        // Creamos una orden con la cadena de texto con la sentencia UPDATE
        SQLiteCommand command = connection.CreateCommand();
        command.CommandText = SQLUpdateArchivoCopiado;

        // Añadimos los parámetros Name, Surname y UserId
        command.Parameters.AddWithValue("ArchivoCopiado", e.Name);
        command.Parameters.AddWithValue("Letra", letra);

        // Ejecutamos la sentencia UPDATE y cerramos la conexión
        command.ExecuteNonQuery();


        // SUMAR EL TAMANO DEL ARCHIVO PARA OBTENER EL TOTAL COPIADO
        SQLiteCommand commando = connection.CreateCommand();
        commando.CommandText = SQLSetIncrementTotalCopiado;

        var info = new FileInfo(e.FullPath);
        var theSize = info.Length;

        commando.Parameters.AddWithValue("TotalCopied", theSize);
        commando.Parameters.AddWithValue("Letra", letra);

        // Ejecutamos la sentencia UPDATE y cerramos la conexión
        commando.ExecuteNonQuery();



        connection.Close();


    }


}
void FileSystemWatcherDeleted(object sender, System.IO.FileSystemEventArgs e)
{

    FileInfo fileInfo = new FileInfo(e.FullPath);
    String letra = e.FullPath.Substring(0, 3);


    if (connection.State != ConnectionState.Open)
        connection.Open();

    // Creamos una orden con la cadena de texto con la sentencia UPDATE
    SQLiteCommand command = connection.CreateCommand();
    command.CommandText = SQLUpdateArchivoEliminado;

    // Añadimos los parámetros Name, Surname y UserId
    command.Parameters.AddWithValue("ArchivosEliminados", e.Name);
    command.Parameters.AddWithValue("Letra", letra);

    // Ejecutamos la sentencia UPDATE y cerramos la conexión
    command.ExecuteNonQuery();
    connection.Close();




}
  • 1
    Welcome to stack overflow. It's really hard to determine what the issue may be, since you haven't provided any of the code you are using to setup the FileSystemWatcher. Please add your code to the question. – Brendan Green May 05 '19 at 21:56
  • Are you using [FileSystemWatcher.IncludeSubdirectories](https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.includesubdirectories?view=netframework-4.8)? – Dennis Kuypers May 05 '19 at 22:01
  • Please, post a piece of code to show what you've tried. – Felipe Oriani May 05 '19 at 22:04
  • Yes, i am already usin Include Subdirectories, I just add my code in the comments, thanks for the fast reply. – Ernesto Alejandro Quintero Sur May 05 '19 at 22:08
  • You posted [too much code](https://idownvotedbecau.se/toomuchcode/). You need to reduce it to a [minimal complete verifiable example](https://stackoverflow.com/help/mcve). In doing that you may even solve the problem yourself. – Dour High Arch May 05 '19 at 22:28
  • 1
    Since you're not specifying a `NotifyFilter`, you're using the default: `NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.DirectoryName`. This will also notify when a Directory is created. Since the file length is `0`. your `IsFileReady` proc will return false and you have locked your event handler forever (you could also remove that check completely). BTW, everything you're doing in the FSW event handlers doesn't belong there, you have to move it to another thread. – Jimi May 05 '19 at 23:10
  • Thank Jimi, I am going to do what you are saying, i let you know .... greets for you – Ernesto Alejandro Quintero Sur May 05 '19 at 23:14
  • Thanks jimmi, I changed it and its working perfectly, thanks – Ernesto Alejandro Quintero Sur May 06 '19 at 00:56

1 Answers1

0

Thanks to Jimmi's comment i have already solved my problem.

I just change my isFileReady proc. This is my new code and it's working perfectly. Thanks to all for your replies.!

 private bool isFileReady(string FilePath)

    {

        try

        {

            if (File.Exists(FilePath))

                using (File.OpenRead(FilePath))

                {

                    return true;

                }

            else

                return false;

        }

        catch (Exception)

        {

            Thread.Sleep(100);

            return isFileReady(FilePath);

        }

    }




    void FileSystemWatcherCreated(object sender, System.IO.FileSystemEventArgs e)
    {





        if (isFileReady(e.FullPath))

        {

            FileInfo fileInfo = new FileInfo(e.FullPath);
            String letra = e.FullPath.Substring(0, 3);


            if (connection.State != ConnectionState.Open)
                connection.Open();

            // Creamos una orden con la cadena de texto con la sentencia UPDATE
            SQLiteCommand command = connection.CreateCommand();
            command.CommandText = SQLUpdateArchivoCopiado;

            // Añadimos los parámetros Name, Surname y UserId
            command.Parameters.AddWithValue("ArchivoCopiado", e.Name);
            command.Parameters.AddWithValue("Letra", letra);

            // Ejecutamos la sentencia UPDATE y cerramos la conexión
            command.ExecuteNonQuery();


            // SUMAR EL TAMANO DEL ARCHIVO PARA OBTENER EL TOTAL COPIADO
            SQLiteCommand commando = connection.CreateCommand();
            commando.CommandText = SQLSetIncrementTotalCopiado;

            var info = new FileInfo(e.FullPath);
            var theSize = info.Length;

            commando.Parameters.AddWithValue("TotalCopied", theSize);
            commando.Parameters.AddWithValue("Letra", letra);

            // Ejecutamos la sentencia UPDATE y cerramos la conexión
            commando.ExecuteNonQuery();



            connection.Close();

        }