国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#采用FileSystemWatcher實現監視磁盤文件變更的方法

2019-10-29 21:45:48
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了C#采用FileSystemWatcher實現監視磁盤文件變更的方法,詳細分析了FileSystemWatcher的用法,并以此為基礎實現監視磁盤文件變更,是非常實用的技巧,具有一定的借鑒價值,需要的朋友可以參考下
 

本文實例講述了C#采用FileSystemWatcher實現監視磁盤文件變更的方法。分享給大家供大家參考。具體實現方法如下:

簡化需求:有一個簡化了的需求是這樣的:有一個拍照程序在運行,一旦抓拍之后則將圖片文件存儲至某目錄,然后圖片要上傳至遠程服務器并update數據庫。

原需求:原先的需求是這樣的:有一臺PDA掃碼槍,一個IP照相機放置在下線區傳送帶上方。當PDA掃描箱子上的條碼,觸發相機拍照,將圖片流傳至遠端服務器,找到對應的條碼,將圖片存儲并更新數據庫。

然而我不知道PDA掃描的瞬間如何與IP相機通信(藍牙或WLAN?),其實關鍵是我不知道怎樣使用IP相機的外觸發功能,增加藍牙觸發器?也不知道怎樣hack或ssh到這個相機(應該是linux的吧),所以只能先使用簡化需求的版本。

而簡化需求的版本,關鍵就是監視文件夾內容變化與上傳文件流。

昨天問了下度娘,C#中的監視組件名字叫做FileSystemWatcher。

于是寫了個demo,可以監視所有邏輯盤或者某個文件夾。

使用方法:

1.直接打開是監視所有邏輯磁盤文件變化。

C#采用FileSystemWatcher實現監視磁盤文件變更的方法

2.或者傳遞參數,監視某一路徑文件變化。如圖,監視e盤

C#采用FileSystemWatcher實現監視磁盤文件變更的方法

源代碼如下:

 

復制代碼代碼如下:

namespace FileSystemWatcherDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //watcher組
            FileSystemWatcher[] watchers;

 

            //若未傳遞參數,則監視所有文件系統,包括CD-ROM(不可用),可移動磁盤(不可用)等
            if (args.Length == 0)
            {
                string[] drivers = Directory.GetLogicalDrives();
                watchers = new FileSystemWatcher[drivers.Length];

                for (int i = 0; i < drivers.Length; i++)
                {
                    try
                    {
                        watchers[i] = new FileSystemWatcher { Path = drivers[i] };
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceWarning(ex.Message);
                    }
                }
            }
            else
            {
                watchers = new FileSystemWatcher[1];
                watchers[0] = new FileSystemWatcher { Path = args[0] };
            }

            foreach (FileSystemWatcher w in watchers)
            {
                if (w == null) continue;

                w.Filter = "*";
                w.IncludeSubdirectories = true;
                w.EnableRaisingEvents = true;

                w.Created += onFileSystem_Changed;
                w.Deleted += onFileSystem_Changed;
                w.Changed += onFileSystem_Changed;
                w.Renamed += watcher_Renamed;
            }

            Console.ReadLine();
        }

        #region [ 檢測文件是否占用 ]
        /// <summary>
        /// 檢測文件是否占用
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        static bool IsFileReady(string filename)
        {
            var fi = new FileInfo(filename);
            FileStream fs = null;
            try
            {
                fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.None);
                return true;
            }
            catch (IOException)
            {
                return false;
            }

            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }
        #endregion

        private static volatile object _lock = true;
        static void onFileSystem_Changed(object sender, FileSystemEventArgs e)
        {
            lock (_lock)
            {
                Console.ForegroundColor = ConsoleColor.DarkGray;
                Console.Write("[");
                Console.Write(DateTime.Now.ToString("HH:mm:ss"));
                Console.Write("] ");

                switch (e.ChangeType.ToString().ToLower())
                {
                    case "created":
                        //while (!IsFileReady(e.FullPath))
                        //{
                        //    if (!File.Exists(e.FullPath))
                        //        return;
                        //    Thread.Sleep(100);
                        //}
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write(e.ChangeType);
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.Write(" ");
                        Console.Write(e.Name);
                        Console.Write(" ");
                        Console.ForegroundColor = ConsoleColor.DarkGray;
                        Console.Write(e.FullPath);

                        break;
                    case "deleted":
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write(e.ChangeType);
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.Write(" ");
                        Console.Write(e.Name);
                        Console.Write(" ");
                        Console.ForegroundColor = ConsoleColor.DarkGray;
                        Console.Write(e.FullPath);
                        break;
                    case "changed":
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.Write(e.ChangeType);
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.Write(" ");
                        Console.Write(e.Name);
                        Console.Write(" ");
                        Console.ForegroundColor = ConsoleColor.DarkGray;
                        Console.Write(e.FullPath);
                        break;
                }

                Console.Write("/r/n");
            }
        }
        static void watcher_Renamed(object sender, RenamedEventArgs e)
        {
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.Write(e.ChangeType);
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(" ");
            Console.Write(e.OldName);
            Console.Write(e.OldFullPath);
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write(" ");
            Console.Write(e.Name);
            Console.Write(e.FullPath);
            Console.Write(Thread.CurrentThread.Name);
            Console.Write("/r/n");
        }
    }
}

 

希望本文所述對大家的C#程序設計有所幫助。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 石景山区| 榆树市| 长宁县| 陇川县| 高青县| 昌平区| 龙门县| 平南县| 长泰县| 嵩明县| 类乌齐县| 即墨市| 筠连县| 铜陵市| 太原市| 碌曲县| 台南县| 抚松县| 襄汾县| 宜春市| 大足县| 上栗县| 海门市| 石门县| 湾仔区| 青神县| 台湾省| 青铜峡市| 伊宁市| 岢岚县| 富阳市| 亚东县| 安龙县| 乃东县| 霍林郭勒市| 阿克苏市| 苍梧县| 绥宁县| 方城县| 湄潭县| 阜宁县|