C#監(jiān)聽txt文檔獲取新數(shù)據(jù)方式
前言
之前有個需求就是監(jiān)聽文件夾中最新的txt文檔獲取最新數(shù)據(jù),還有其他功能,
比如:開機自啟動、只在任務(wù)管理器關(guān)閉、阻止Ctrl+C中斷等,對此作個記錄,整理代碼。
一、監(jiān)聽txt文檔增加數(shù)據(jù)
代碼如下:
static void RunMainLogic()
{
//1. 獲取程序基目錄
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
//2.拼接相對路徑(目標路徑 - 文件夾)并轉(zhuǎn)換為絕對路徑
string relativePath = @"..\..\..\..\TotalTest\Debug";
string targetDir = Path.GetFullPath(Path.Combine(baseDir, relativePath));
//3.檢查目標目錄是否存在
if (!Directory.Exists(targetDir))
{
Console.WriteLine("目標目錄不存在:{" + targetDir + "}");
return;
}
//4.獲取所有名稱包含“Test”的子文件夾,并按時間排序
var latsetTestDir = Directory.GetDirectories(targetDir, "*Test*", SearchOption.TopDirectoryOnly)
.Select(dir => new DirectoryInfo(dir))
.OrderByDescending(dir => dir.LastWriteTime)
.FirstOrDefault();
if (latsetTestDir == null)
{
Console.WriteLine("Test文件夾路徑不存在!");
return;
}
string folderPath = latsetTestDir.FullName;
string str = "開始監(jiān)控文件夾: {" + folderPath + "}";
Console.WriteLine(str);
//txt文檔監(jiān)聽
TextFileWatcher watcher = new TextFileWatcher(folderPath); //先被執(zhí)行
watcher.DataReceived += OnDataReceived; //訂閱事件
watcher.SetNewestFileAsTarget();
}
//訂閱事件
static void OnDataReceived(object sender, string data)
{
string StrLine = data; //需要的數(shù)據(jù)
}
二、其他功能
1. 設(shè)置開機自啟動
代碼如下:
static void SetAutoStart(string appName, string appPath)
{
RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue(appName, appPath);
key.Close();
}
作用:將程序添加到注冊表啟動項,實現(xiàn)開機自動運行。
調(diào)用方式:
SetAutoStart("MyConsoleApp", System.Reflection.Assembly.GetExecutingAssembly().Location);
2. 禁止控制臺窗口關(guān)閉按鈕
代碼如下:
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);
private const uint SC_CLOSE = 0xF060;
private const uint MF_GRAYED = 0x00000001;
static void DisableCloseButton()
{
IntPtr hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
IntPtr hMenu = GetSystemMenu(hWnd, false);
EnableMenuItem(hMenu, SC_CLOSE, MF_GRAYED);
}
作用:禁用窗口的x關(guān)閉按鈕,用戶無法直接關(guān)閉程序。
3. 阻止Ctrl + C中斷
代碼如下:
Console.CancelKeyPress += (sender, e) => e.Cancel = true;
作用:防止用戶按 Ctrl + C 終止程序。
4. 防止程序退出(無限循環(huán))
代碼如下:
while(true)
{
Thread.Sleep(1000); //防止CPU占用過高
}
作用:讓程序無限運行,除非任務(wù)管理器終止或程序報錯。
總結(jié)
如將開機自啟動和只能在任務(wù)管理器關(guān)閉放到監(jiān)聽txt文檔功能。
在主函數(shù)中,代碼如下:
//1. 設(shè)置開機自啟動
SetAutoStart("ConsoleApplication1", System.Reflection.Assembly.GetExecutingAssembly().Location);
//2. 禁用關(guān)閉按鈕
DisableCloseButton();
//3. 阻止Ctrl+C 關(guān)閉
Console.CancelKeyPress += (sender, e) =>
{
e.Cancel = true; // 阻止默認行為
Console.WriteLine("Ctrl+C 被禁用,無法關(guān)閉程序。");
};
//4. 主要業(yè)務(wù)邏輯
RunMainLogic();
//5. 防止程序退出(無限循環(huán))
while (true)
{
Thread.Sleep(1000); // 每秒鐘檢查一次(防止 CPU 占用過高)
}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
c# WPF中通過雙擊編輯DataGrid中Cell的示例(附源碼)
這篇文章主要介紹了c# WPF中通過雙擊編輯DataGrid中Cell的示例(附源碼),幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下2021-03-03
C#中String.LastIndexOf方法小結(jié)
String.LastIndexOf()是C#中string類的一個方法,它用于在字符串中查找指定子字符串(或字符)最后一次出現(xiàn)的位置,并返回其索引,本文主要介紹了C#中String.LastIndexOf方法小結(jié),感興趣的可以了解一下2024-01-01

