Как получить номер идентификатора наблюдателя файловой системы? - PullRequest
0 голосов
/ 18 февраля 2020

Основной код:

    static void Main(string[] args)
    {

        MySqlConnection mcon = new MySqlConnection("connection credentials...");
        MySqlDataReader myreader = null;
        MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
        mcon.Open();

        myreader = cmd.ExecuteReader();

        //List of path's from MySQL table
        List<String> list = new List<String>();

        while (myreader.Read())
        {
            //Appending the list of all path names from MySQL table
            list.Add(myreader[1].ToString());
            //Retrieving id number of path from MySQL table (see list before 'private static void directoryChange')
            list2.Add(myreader.GetInt32(0));


        }
        mcon.Close();

        //This watches all path's listed in MySQL table
        foreach (string i in list)
        {

            Console.WriteLine(i);
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = Path.GetDirectoryName($@"{i}"); //get specific files listed in MySQL table
            watcher.Filter = Path.GetFileName($@"{i}");
            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = true;

            watcher.Created += directoryChange;
            watcher.Deleted += directoryChange;
            watcher.Renamed += onRename;
        }

        Console.Read();
    }

    //List of Id numbers from MySQL table
    static List<int> list2 = new List<int>();

    private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
    {
                if (e.ChangeType == System.IO.WatcherChangeTypes.Deleted){
                Console.WriteLine($"Deleted {e.FullPath}"); //Here I need to get the id number of file that has been deleted
                 }
    }

Цель:

Моя цель - получить id число от MySQL из файл, который был удален.

  • Файловая система просматривает только файлы, перечисленные в таблице MySQL.
  • Но как мне распечатать идентификационный номер только что удаленной записи ? в пределах каталога Изменить?

Обновление:

Вот куда я попал:

static void Main(string[] args)
{

    MySqlConnection mcon = new MySqlConnection("connection credentials...");
    MySqlDataReader myreader = null;
    MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
    mcon.Open();

    myreader = cmd.ExecuteReader();

    //List of path's from MySQL table
    List<String> list = new List<String>();
   //List of Id numbers from MySQL table
   static List<int> list2 = new List<int>();

    while (myreader.Read())
    {
        //Appending the list of all path names from MySQL table
        list.Add(myreader[1].ToString());
        //Retrieving id number of path from MySQL table (see list before 'private static void directoryChange')
        list2.Add(myreader.GetInt32(0));


    }
    mcon.Close();

    //This watches all path's listed in MySQL table
        var data = list.Zip(list2, (n, w) => new {Path= n, ID = w});

        foreach(var nw in data)
        {
            int result = nw.ID;
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = Path.GetDirectoryName($@"{nw.Path}");
            watcher.Filter = Path.GetFileName($@"{nw.Path}");
            watcher.EnableRaisingEvents = true;
            watcher.IncludeSubdirectories = true;

            watcher.Created += directoryChange;
            watcher.Deleted += directoryChange;
            watcher.Renamed += onRename;
        }

    Console.Read();
}
//Tried passing over the id from for loop
static int result;



private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
{
            if (e.ChangeType == System.IO.WatcherChangeTypes.Deleted){
            Console.WriteLine($"Deleted {e.FullPath}"); 
            Console.WriteLine(result);
             }
}

Это не работает, потому что результат отображается как 0. Посмотрим, смогу ли я это исправить.

1 Ответ

1 голос
/ 18 февраля 2020

Итак, чтобы напомнить, что я проанализировал из вашего кода:

  • Вы читаете список файлов из SQL таблицы
  • Вы инициализируете FileSystemWatcher в каталоге каждого файла с фильтром по имени каждого файла
  • Вы связываете все прослушиватели событий всех наблюдателей с одинаковыми обработчиками
  • В обработчике, где вы получаете только полный путь к файлу, который вы ' Если вас предупреждают, вы хотите знать «id» (т. е. первичный ключ таблицы) для данного пути

Итак, просто держите словарь с данными вместо двух списков или одна переменная c переменная?

// Class-level field
private static Dictionary<string, int> fileList = new Dictionary<string, int>();

// Then while reading the data:
while (myreader.Read())
{       
    // Use path as a key to the id, so you can use the path later to look up the key
    fileList[myreader[1].ToString()] = myreader.GetInt32(0);
}

foreach(var nw in fileList)
{
    // ...
}

А потом в вашем обработчике событий:

private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
{
    if (e.ChangeType == System.IO.WatcherChangeTypes.Deleted)
    {
        if (fileList.TryGetValue(e.FullPath, out var id))
        {
            Console.WriteLine(id);
        }
        else
        {
            Console.WriteLine($"Path '{e.FullPath}' not present in dictionary?");
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...