.net core 监控文件

.net core 监控文件

注: 建议 core 2.2 及以上

参考官方文档

https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.path

安装包:
System.Security.Permissions
Newtonsoft.Json
System.Text.Encoding.CodePages

// An highlighted block
using Newtonsoft.Json;
using System;
using System.Collections;
using System.IO;
using System.Security.Permissions;
namespace ConsoleApp3
{
    public class Program
    {
        public static void Main()
        {
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            Run();
        }

        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        private static void Run()
        {
    
            // Create a new FileSystemWatcher and set its properties.
            using (FileSystemWatcher watcher = new FileSystemWatcher())
            {
                watcher.Path = @"C:\Users\user\Desktop";
                //不监控子目录
                watcher.IncludeSubdirectories = false; 
                // Watch for changes in LastAccess and LastWrite times, and
                // the renaming of files or directories.
                //在这只监控文件的修改如果需要监控别的配置上就好
                watcher.NotifyFilter = NotifyFilters.LastWrite;
                                

                // Only watch text files.
                //只读取这个一个文件  如果监控所有的  watcher.Filter = "*.txt";
                watcher.Filter = "record.txt";

                // Add event handlers.
				//监控文件发生修改事件 并调用自己定义的触发事件
                watcher.Changed += OnChanged;
                //watcher.Created += OnChanged;
                //watcher.Deleted += OnChanged;
                //watcher.Renamed += OnRenamed;

                // Begin watching. 开启监控
                watcher.EnableRaisingEvents = true;
                // Wait for the user to quit the program.
                Console.WriteLine("Press 'q' to quit the sample.");
                while (Console.Read() != 'q') ;
            }
        }

        // Define the event handlers.
        //private static void OnChanged(object source, FileSystemEventArgs e) => new Thread(ReadFile).Start();
        //执行文件内容修改后触发的事件
        private static void OnChanged(object source, FileSystemEventArgs e) => ReadFile();
        // Specify what is done when a file is changed, created, or deleted.
        //Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");

        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}");
		//我这 : 读取一个文件 把第一行 第二行放入消息队列然后从消息队列读取出来转为json格式
        public static void ReadFile()
        {
            Queue queue1 = new Queue();
            Queue queue2 = new Queue();
            Hashtable hashtable = null;
            hashtable= new Hashtable();
            string filePath = @"C:\Users\user\Desktop\record.txt";
                 FileStream fs = null;
                 //我这  只读不写
                 fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                 StreamReader sr = null;
                 //转为中文需要安装 System.Text.Encoding.CodePages
                 sr=new StreamReader(fs, System.Text.Encoding.GetEncoding("GB2312"));
                while (sr.Peek() != -1)
                {
                    string result = sr.ReadLine();
                    string[] arry = result.Split(',');
                    if (queue1.Count != arry.Length)
                    {
                        foreach (string str in arry)
                        {
                            queue1.Enqueue(str);
                        }
                    }
                    else
                    {
                        foreach (string str in arry)
                        {
                            queue2.Enqueue(str);
                        }
                    }
                }
                sr.Close();
                fs.Close();
                fs.Dispose();

            int counter = queue1.Count;
            for (int i = 0; i < counter; i++)
            {
                hashtable[queue1.Dequeue()] = queue2.Dequeue();
            }
            string msg = JsonConvert.SerializeObject(hashtable);
           // hashtable.Clear();
            Console.WriteLine(msg);
        }
    }
}

你可能感兴趣的:(.net,core,文件监控,技术,c#,软件开发)