C# 文件监听,文件写入,文件读取

最近写了个文件监听,本来打算用死循环做的,后面因为客户的需求角度刁钻,所以,换成了文件监听。

需求背景,我写入文件,对方读取,对方做了逻辑处理,将返回结果写入另一个文件, 然后我读取另一个文件,做逻辑判断。

由于我监听到对方写入的文件后是需要返回bool类型的,所以先定义一个全局的bool类型的变量,承接返回值:

//默认false
bool flag=false;

写入文件:

public string CreateFile(string barcode, double weight, double length, double width, double height, double volume)
        {
          
        
       
            try
            {
       //写入文件的文件路径,无后缀
       string strPath = @"C:\Users\Public\Libraries\PackageSharedInfo";
      ///需要写入的内容,这里可以用字典序列化的方式实现
            string Tname = "{" + '"' + "pnos" + '"' + ":" + "[" + '"' + barcode + '"' + "]" + "," + '"' + "weight" + '"' + ":" + weight + ',' + '"' + "length" + '"' + ':' + length + "," + '"' + "width" + '"' + ':' + width + ',' + '"' + "height" + '"' + ':' + height + '}';
            Logger.Debug("日志输出:" + Tname);
    
                 //文件写入,这里采用WriteAllText写入,用文件流的话,可能会触发两次监听事件。
                File.WriteAllText(strPath, Tname);
                Logger.Debug("写入成功:" );
                return "";
            }
            catch (Exception ex)
            {
                Logger.Error("程序异常,调用CreateFile失败,异常原因:" + ex);
                return "";
            }
        }

创建监听对象:

public bool GetContentByTxt()
        {
            //监听路径
            watcher.Path = @"C:\Users\Public\Libraries";
            //监听的文件变动类型
            watcher.NotifyFilter = NotifyFilters.LastWrite
                                 | NotifyFilters.Attributes
                                 | NotifyFilters.CreationTime
                                 | NotifyFilters.DirectoryName
                                 | NotifyFilters.FileName
                                 | NotifyFilters.LastAccess
                                 | NotifyFilters.LastWrite
                                 | NotifyFilters.Security
                                 | NotifyFilters.Size; 
             //监听的具体文件的文件名称                    
            watcher.Filter = "ipc_channel";
            //创建事件委托
            watcher.Changed += new FileSystemEventHandler(OnChange);
            //开启监听
            watcher.EnableRaisingEvents = true;
            //返回bool类型值
            return flag;
        }

创建监听对象后,需要事件委托对象:

private void OnChange(object source,FileSystemEventArgs e)
 {
     //监听事件处理逻辑
     //由于此处无法返回bool类型,所以重写一个方法,并调用
            GetIPC();
 }

监听到文件变动后,做逻辑处理:

public bool GetIPC() {
            try
            {
            //需要监听的文件的路径
               string path = @"C:\Users\Public\Libraries\ipc_channel";
               //创建文件流
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
               // 读取监听的文件内容
                StreamReader reader = new StreamReader(fs);
                string conStr = reader.ReadLine();
                 Logger.Debug("当前conStr输出" + conStr);
                  //反序列化ipc_channel
                var ipcjson = JsonConvert.DeserializeObject<SystemIPC>(conStr);
                Logger.Debug("当前ipcjson输出" + ipcjson);
               
                   //单号一致,判断是否成功
                    if (ipcjson.cmd == "resume")
                    {
                        Logger<TaiGuoKY>.Debug("返回成功,当前返回" + ipcjson.cmd);
                           //监听完成后关闭监听
                    MessageBox.Show("程序变动,监听成功");
                    flag = true;
                    return true;
                    }
                    else
                    {
                        Logger<TaiGuoKY>.Debug("返回失败,当前返回" + ipcjson.cmd);
                           //监听完成后关闭监听
                    MessageBox.Show("程序变动");
                    flag = false;
                        return false;
                    }
                }
     catch (Exception ex)
            {
                Logger<TaiGuoKY>.Error("程序异常,调用GetContentByTxt失败,异常原因+" + ex);
                //监听完成后关闭监听
                watcher.EnableRaisingEvents = false;
                flag = false;
                return false;
            }

        }

用到了反序列化,当然得实例化类:

public class SystemIPC
        {
            public string pno { get; set; }
            public string cmd { get; set; }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值