HarmonyLib 使用和 C# 文件操作方法

//Hook的lib库代码
using HarmonyLib;
using System.Collections.Generic;
using System.IO;


namespace ClassLibrary1
{
    
    public class Main
    {
        // we use a default injection method name in order to execute our code in the remote process
        public static int Inject(string str)
        {
            MyFile.WriteFileAppend("----------------start log----------------");
            var harmony = new Harmony("com.example.patch");
            harmony.PatchAll();
            return 0;

        }
    }

    //hook 发送数据的类和方法
    [HarmonyPatch(typeof(Hook的类名))]  //类
    [HarmonyPatch("Hook的方法名")]  //方法,防止写错尽量用nameof()
    class Patch01
    {


        //Prefix返回一个bool,如果false,则不执行后续Prefix,不执行原始方法
        [HarmonyPrefix]
        static bool Prefix(hook类名 __instance,string sendData, ref string reciveData, int nrc78LoopTime = 0, bool nrc78InfinityWait = false, uint judgeLID = 16777215U)
        {
            reciveData =  MyFile.GetReciveData(sendData);
            MyFile.WriteFileAppend(sendData + "," + reciveData);
            return false;
        }



        //Postfix永远执行
        [HarmonyPostfix]
        static void Postfix(ref int __result)  //__result表示Hook方法的返回值
        {
            __result = 0;
        }
    }

    class MyFile {
       
        //写入文件和读取文件
        public static string strOutLogPath= "log.txt";
        public static string strCmdPath = "cmd.txt";
        public static void WriteFileAppend(string info) {
            FileStream fs = new FileStream(strOutLogPath, FileMode.Append, FileAccess.Write);
            //获得字节数组
            info += "\r\n";
            byte[] data = System.Text.Encoding.Default.GetBytes(info);//info为要追加的数据//设定书写的开始位置为文件的末尾 
            fs.Position = fs.Length;
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();
        }

        public static string GetReciveData(string strSendData) {
            string strResult = "";
            StreamReader sr = new StreamReader(strCmdPath);
            string line;
            // ReadLine()一行一行的循环读取
            //当然可以直接ReadToEnd()读到最后
            Dictionary<string, string> hashMap = new Dictionary<string, string>();
            while ((line = sr.ReadLine()) != null)
            {
                string[] strs = line.Split(',');
                if (strs.Length == 2)
                {
                    if (!hashMap.ContainsKey(strs[0])) {
                        hashMap.Add(strs[0], strs[1]);
                    }
                }
            }

            if (hashMap.ContainsKey(strSendData))
            {
                strResult = hashMap[strSendData];
            }
            sr.Close();
            return strResult;
        }
    }
}

注入的代码

//注入代码界面
using FastWin32.Diagnostics;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {

        public static string strOutLogPath = "log.txt";
        public static string strCmdPath = "cmd.txt";
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "启动程序";
            button1.Text = "发送命令工具 选择 ClassLibrary3.dll";
            Process[] processes = Process.GetProcesses();
            foreach (Process process in processes)
            {
                if (process.ProcessName.Equals(""))
                {
                    textBox1.Text = Convert.ToString(process.Id) ;
                }

            }
            string pathFile = AppDomain.CurrentDomain.BaseDirectory + "ClassLibrary3.dll";


            if (File.Exists(pathFile) && textBox1.Text!="")
            {

                uint id = Convert.ToUInt32(textBox1.Text);
                Injector.InjectManaged(id, pathFile, "ClassLibrary1.Main", "Inject", "", out int returnValue);
                MessageBox.Show($"存在文件   {pathFile} \r\n 执行成功 {returnValue} \r\n 日志文件路径:{strOutLogPath} \r\n : {strCmdPath} ");
                Dispose();
            }
            
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            

            if (textBox1.Text == "")
            {
                MessageBox.Show("在任务管理器查看  MUT3_SE.exe PID,手动填上");
            }
            else {
                //Nuget安装FastWin32
                string pathFile = AppDomain.CurrentDomain.BaseDirectory + "ClassLibrary3.dll";
                if (File.Exists(pathFile))
                {
 
                    uint id = Convert.ToUInt32(textBox1.Text);  //在任务管理器看02_目标winform.exe的PID,手动填上
                    Injector.InjectManaged(id, pathFile, "ClassLibrary1.Main", "Inject", "", out int returnValue);
                    MessageBox.Show($"存在文件   {pathFile} \r\n 执行成功 {returnValue}  \r\n :{strOutLogPath} \r\n : {strCmdPath} ");

                }
                else {

                    OpenFileDialog dialog = new OpenFileDialog();
                    dialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    if (dialog.ShowDialog() == DialogResult.OK)  //
                    {
                        uint id = Convert.ToUInt32(textBox1.Text);  //
                        Injector.InjectManaged(id, dialog.FileName, "ClassLibrary1.Main", "Inject", "", out int returnValue);
                        MessageBox.Show($"   {pathFile} \r\n  {returnValue}  \r\n :{strOutLogPath} \r\n : {strCmdPath} ");

                    }

                }
                
                Dispose();
            }
            
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Process[] processes = Process.GetProcesses();
            foreach (Process process in processes)
            {
                if (process.ProcessName.Equals("应用程序名称"))
                {
                    textBox1.Text = Convert.ToString(process.Id);
                }

            }
        }


    }


}

建立C#注入lib库工程方法

建立C#注入工程界面

添加注入工程缺少的依赖lib库

添加FastWin32  ,HarmonyLib

添加注入库依赖项

报错和解决办法

1.注入库没有用,确保注入的lib库和要注入的程序的框架保持一致,例如注入代码为.net 4框架版本,那么注入工程选用.net 4框架, 保持编译出来的字节码是一致的

2.缺少.net框架  ,进行安装

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值