[C#] Delegate委派實作Folder By Folder檔案處理

  • 1441
  • 0

摘要:[C#] Delegate委派實作Folder By Folder檔案處理

委派如同C語言的方法指標

在C#語言是一個類別關鍵字

使用時必須宣告為物件來使用

 

本實作用於有兩種檔案處理的方法

共通點是都需要Folder By Folder處理所有資料夾內的檔案

為了不重複Folder By Folder部分程式碼(有遞迴)

所以需要用到方法指標

檔案處理方法一

                refHandleFileFunction refFunction = new refHandleFileFunction(HandleFile_1);
                delegateHandleFolderByFolder(rootFolder, refFunction);

檔案處理方法二

                refHandleFileFunction refFunction = new refHandleFileFunction(HandleFile_2);
                delegateHandleFolderByFolder(rootFolder, refFunction);

 

以下是Folder By Folder實作部分

        private void delegateHandleFolderByFolder(string rootFolder, refHandleFileFunction delegateHandleFileFunction)
        {            
            string[] files = System.IO.Directory.GetFiles(rootFolder);
            foreach (string file in files)
            {
                delegateHandleFileFunction.Invoke(file);
            }
            string[] folders = System.IO.Directory.GetDirectories(rootFolder);            
            foreach (string folder in folders)
            {                
                delegateHandleFolderByFolder(folder, delegateHandleFileFunction);
            }
        }
        private delegate void refHandleFileFunction(string file);

        private void HandleFile_1(string file)
        {
        }

        private void HandleFile_2(string file)
        {
        }