FileSystemWatcher類監控文件的更改狀態並且實時備份文件

来源:https://www.cnblogs.com/ryzen/archive/2017/12/26/8117736.html
-Advertisement-
Play Games

首先這是我自己在一個任務需求裡面所要用到的,大致的代碼如下:我把監視文件和備份文件的方法封裝到一個WatcherAndBackup 類中了,但是總感覺封裝的不是很好,有大牛能夠指出改正之處在此留言,謝謝指點了哈!!,主要監視文件用到的類就是在sysytem.IO 裡面的FileSystemWatch ...


首先這是我自己在一個任務需求裡面所要用到的,大致的代碼如下:我把監視文件和備份文件的方法封裝到一個WatcherAndBackup

類中了,但是總感覺封裝的不是很好,有大牛能夠指出改正之處在此留言,謝謝指點了哈!!,主要監視文件用到的類就是在sysytem.IO

裡面的FileSystemWatcher,然後在一個控制台裡面創建類WatcherAndBackup的實例並且運行就行

 

 1  class WatcherAndBackup
 2     {
 3         string sourcefile = "";//源文件
 4         string targetfile = "";//目標文件
 5         string targetPath = "";//目標路徑
 6         public WatcherAndBackup(string Sourcefile,string Targetfile,string TargetPath)
 7         {
 8             sourcefile = Sourcefile;targetfile = Targetfile;targetPath = TargetPath;
 9         }
10        
11         public void backup(string sourcefile,string targetfile,string targetPath)
12         {
13             try
14             {
15                 if (!Directory.Exists(targetPath))
16                 {
17                     Directory.CreateDirectory(targetPath);
18                     
19                 }
20                 File.Copy(sourcefile, targetfile, true);
21 
22             }
23             catch { }
24         }
25         #region 實時監視文件更改並且備份文件
26         public void watcherfile(string path,string file)
27         {
28             FileSystemWatcher fsw = new FileSystemWatcher(path, file);
29             fsw.Changed += new FileSystemEventHandler(change_watcher);
30             fsw.Created += new FileSystemEventHandler(change_watcher);
31             fsw.Deleted += new FileSystemEventHandler(change_watcher);
32             fsw.Renamed += new RenamedEventHandler(rename_watcher);
33             fsw.EnableRaisingEvents = true;
34             Console.WriteLine("開始監視。。。。");
35             fsw.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName
36                 | NotifyFilters.LastAccess | NotifyFilters.Security | NotifyFilters.Size | NotifyFilters.LastWrite;
37             fsw.IncludeSubdirectories = true;
38         }
39         public void change_watcher(object sender,FileSystemEventArgs e)
40         {
41            
42             var wacher = sender as FileSystemWatcher;
43             wacher.EnableRaisingEvents = false;
44             
45             if (e.ChangeType==WatcherChangeTypes.Changed)
46             {
47                 Console.WriteLine("正在備份。。。");
48                     backup(sourcefile,targetfile,targetPath);
49                     Console.WriteLine("備份成功。。。");
50                                
51             }
52             else if (e.ChangeType==WatcherChangeTypes.Created)
53             {
54                 Console.WriteLine("{0},{1},{2}", e.ChangeType, e.FullPath, e.Name);
55                 return;
56             }
57             else if (e.ChangeType==WatcherChangeTypes.Deleted)
58             {
59                 Console.WriteLine("{0},{1},{2}", e.ChangeType, e.FullPath, e.Name);
60                 return;
61             }
62             wacher.EnableRaisingEvents = true;
63         }
64         public void rename_watcher(object sender,RenamedEventArgs e)
65         {
66             Console.WriteLine("{0},{1},{2}", e.ChangeType, e.FullPath, e.Name);
67         }
68         #endregion
69 
70     }
 static void Main(string[] args)
        {
            WatcherAndBackup bk = new WatcherAndBackup(@"D:\gg\config.xml", @"D:\gg\backup\config.xml", @"D:\gg\backup");
            bk.watcherfile(@"D:\gg", "config.xml");//監視的文件為D:\gg\config.xml
            Console.Read();         
        }

 在這裡解釋一下:實例類WatcherAndBackup時分別要寫下backup方法的三個參數:sourcefile、targefile、targePath,也就是備份方法的源文件、目標文件、目標文件的目錄,然後在change_watcher方法當中為什麼會有這幾局代碼:

var wacher=sender as FileSystemWatcher;

wacher.EnableRaisingEvents=false;

然後在方法後面:

wacher.EnableRaisingEvents=true;

其實如果不加入這幾句代碼會出現當監控到文件修改時會觸發兩次changed方法,這個修改方法是我在網上找到的一個修改方法

好了,基本也說完了。。。有什麼不正確的地方請各位大牛指正,本就打著學習的態度寫下的。。嘿嘿!!




您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1、引用 SharpCompress.dll 2、代碼 using System;using System.IO;using System.Text;using SharpCompress.Reader;using SharpCompress.Common; ...
  • 預期效果:當Model中的Age數字列值為0時,不顯示該值。 <input type="text" class="form-control onlyPositiveNumber" id="Age" maxlength="3" style="text-align:right;width:80px; " ...
  • 演示產品源碼下載地址:http://www.jinhusns.com ...
  • As Marco Zhou has said in the msdn forum (http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b2428b85-adc9-4a1e-a588-8dbb3b9aac06/):Windows will ...
  • ... ...
  • 回到目錄 你在windows上使用圖像組件沒有任務問題,但部署到linux之後,將註意以下幾點: 安裝gdiplugs的方法 大叔總結的方法ubuntu && debian centos 官方提供的方法: Ubuntu 16.04: Fedora 23: CentOS 7: 感謝各位閱讀! 回到目錄 ...
  • 拆分一個字元串,獲取每一組的key與value。 如字元串: 按照面向對象理念來解決,創建一個對象: class Bf { public string Key { get; set; } public string Value { get; set; } public Bf() { } public ...
  • 在眾多的軟體分類中,有幾類的軟體不是很重要,但也很重要。它們有的是每隔一段時間需要執行一些任務的軟體,我們叫它定時類軟體;還有一種軟體是採集網頁中的數據,我們叫它採集類軟體。 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...