Simple C# File Watcher

vohongnhuy

Internship/Fresher
Mar 11, 2019
21
7
3
27
HCM
SIMPLE C# FILE WATCHER

1. Vấn đề
Giả sử doanh nghiệp có hệ thống File Server nhưng không có các giải pháp về tính sẵn sàng cao và khôi phục sau sự cố, không có giải pháp backup dữ liệu hoặc giải pháp backup không đảm bảo realtime cho dữ liệu thay đổi thường xuyên. Vậy làm thế nào để đảm bảo an toàn cho dữ liệu?

2. Giải pháp
Viết một chương trình đơn giản thực hiện giám sát mọi hoạt động trên một thư mục nào đó (folder A), đồng thời thực hiện mọi hoạt động đó trên một thư mục khác ở một nơi khác – như vậy ta tạo ra bản sao của A (folder A’). Bản sao là bản backup near realtime, tức là mọi thay đổi trên A gần như tức thì cũng dc cập nhật trên A’.

Giả sử hai folder A và A’ đặt ở 2 file server khác nhau, khi đó khi một server fail, ta vẫn còn server còn lại.

Ưu điểm: có một bản sao gần như realtime của dữ liệu, đảm bảo tính sẵn sàng cao và an toàn dữ liệu.

Nhược điểm: do mọi thay đổi đều được đồng bộ, nên nếu thay đổi trên folder A không được kiểm soát, thì folder A’ cũng sẽ thực hiện tương tự, dẫn đến mất dữ liệu.

Mô hình hoạt động:

 filewatcher1


3. Simple App C#
Thực hiện viết một chương trình C# đơn giản thực hiện các chức năng sau:

  • Giám sát mọi hành động trên một folder chỉ định: tạo tệp/thư mục, thay đổi tên tệp/thư mục, xoá tệp/thư mục, thay đổi nội dung tệp.

  • Thực hiện những hành động trên tương tự lên folder A’.
Trong video demo sau: căn cứ vào mô hình hoạt động, Folder A là “D:\testFW”, folder A’ là “D:\desFW”.

Video demo:

Source code tham khảo:
Code:
using System;

using System.IO;

using System.Security.Permissions;


public class Watcher

{

public static void Main()

{

Run();

}


[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]

private static void Run()

{

//Create a new FileSystemWatcher and set its properties.

using (FileSystemWatcher watcher = new FileSystemWatcher(@"D:\testFW"))

{


// Begin watching.

watcher.EnableRaisingEvents = true;

watcher.IncludeSubdirectories = true;


// Only watch text files.

watcher.Filter = "*.*";


// Add event handlers.

watcher.Changed += OnChanged;

watcher.Created += OnCreated;

watcher.Deleted += OnDeleted;

watcher.Renamed += OnRenamed;



// Wait for the user to quit the program.

Console.WriteLine("Press 'q' to quit the sample.");

while (Console.Read() != 'q') ;

}

}

private static void CopyFile(String sourcePath)

{

string destPath = @"D:\DesFW";

string sourPath = @"D:\testFW";


if (System.IO.File.Exists(sourcePath))

{

string destFullPath = sourcePath.Replace(sourPath, destPath);

string destFolder = System.IO.Path.GetDirectoryName(destFullPath);


// To copy a folder's contents to a new location:

// Create a new target folder, if necessary.

if (!System.IO.Directory.Exists(destFolder))

{

System.IO.Directory.CreateDirectory(destFolder);

}

// To copy a file to another location and

// overwrite the destination file if it already exists.


System.IO.File.Copy(sourcePath, destFullPath, true);

}

else

{

string destFullPath = sourcePath.Replace(sourPath, destPath);

string destFolder = destFullPath;

if (!System.IO.Directory.Exists(destFolder))

{

System.IO.Directory.CreateDirectory(destFolder);

}

}

}

private static void RenameFile(String OldsourcePath, String sourcePath)

{

string destPath = @"D:\DesFW";

string sourPath = @"D:\testFW";


if (System.IO.File.Exists(sourcePath))

{

string destFullPath = sourcePath.Replace(sourPath, destPath);

string destOldFullPath = OldsourcePath.Replace(sourPath, destPath);



System.IO.File.Delete(destOldFullPath);

System.IO.File.Copy(sourcePath, destFullPath, true);

}

else

{

string destFullPath = sourcePath.Replace(sourPath, destPath);

string destOldFullPath = OldsourcePath.Replace(sourPath, destPath);


System.IO.Directory.Delete(destOldFullPath);

System.IO.Directory.CreateDirectory(destFullPath);

}

}

private static void DeleteFile(String sourcePath)

{

string destPath = @"D:\DesFW";

string sourPath = @"D:\testFW";



string destFullPath = sourcePath.Replace(sourPath, destPath);

string destFolder = System.IO.Path.GetDirectoryName(sourcePath);


if (System.IO.File.Exists(destFullPath))

{

System.IO.File.Delete(destFullPath);

}

else

{

System.IO.Directory.Delete(destFullPath, true);

}

}

// Define the event handlers.

private static void OnChanged(object source, FileSystemEventArgs e) {

// Specify what is done when a file is changed.

Console.WriteLine($"File: {e.FullPath} {e.ChangeType}. Time: {DateTime.Now.ToLocalTime()}");

CopyFile(e.FullPath);

}

private static void OnCreated(object source, FileSystemEventArgs e) {

// Specify what is done when a file is created.

Console.WriteLine($"File: {e.FullPath} {e.ChangeType}. Time: {DateTime.Now.ToLocalTime()}");

CopyFile(e.FullPath);

}

private static void OnDeleted(object source, FileSystemEventArgs e) {

// Specify what is done when a file is deleted.

Console.WriteLine($"File: {e.FullPath} {e.ChangeType}. Time: {DateTime.Now.ToLocalTime()}");

DeleteFile(e.FullPath);

}

private static void OnRenamed(object source, RenamedEventArgs e) {

// Specify what is done when a file is renamed.

Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}. Time: {DateTime.Now.ToLocalTime()}");

RenameFile(e.OldFullPath, e.FullPath);

}

}
---HẾT---
 

About us

  • Securityzone.vn là một trang web chuyên về an ninh mạng và công nghệ thông tin. Trang web này cung cấp các bài viết, tin tức, video, diễn đàn và các dịch vụ liên quan đến lĩnh vực này. Securityzone.vn là một trong những cộng đồng IT lớn và uy tín tại Việt Nam, thu hút nhiều người quan tâm và tham gia. Securityzone.vn cũng là nơi để các chuyên gia, nhà nghiên cứu, sinh viên và người yêu thích an ninh mạng có thể trao đổi, học hỏi và chia sẻ kiến thức, kinh nghiệm và giải pháp về các vấn đề bảo mật trong thời đại số.

Quick Navigation

User Menu