【问题标题】:How to open a file as binary mode and replace hex strings?如何以二进制模式打开文件并替换十六进制字符串?
【发布时间】:2011-05-30 12:48:12
【问题描述】:

我需要以二进制模式打开并编辑一个可执行文件,将十六进制值替换为字符串。

在 PHP 中,如下所示:

<?php
    $fp = fopen('file.exe', 'r+');
    $content = fread($fp, filesize('file.exe'));
    fclose($fp);
    print $content;
    /* [...] This program cannot be run in DOS mode.[...] */
?>

我如何在 C# 中获得它?

【问题讨论】:

    标签: c# .net binary hex


    【解决方案1】:
    public void Manipulate()
    {
        byte[] data = File.ReadAllBytes("file.exe");
        byte[] newData;
    
        //walkthrough data and do what you need to do and move to newData
    
        File.WriteAllBytes("new_file.exe", newData);
    
    }
    

    【讨论】:

      【解决方案2】:

      您询问有关写入文件的问题,但您的 PHP 代码是用于读取的。要处理文件,您可以使用 FileStream 类

      using(FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Write))
      {
          ....
          stream.WriteByte(byte);
          ....
      }
      

      【讨论】:

        【解决方案3】:

        使用File.ReadAllBytes 以字节数组的形式读取文件的字节。

        byte[] bytes = File.ReadAllBytes('file.exe');
        

        如果您想将其转换为十六进制字符串(我通常建议不要这样做 - 字符串在 C# 中是不可变的,因此即使修改单个字节也需要复制字符串的其余部分)您可以例如使用:

        string hex = BitConverter.ToString(bytes);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-11-17
          • 2013-08-08
          • 2012-06-13
          • 1970-01-01
          • 2016-07-07
          • 2017-03-22
          • 2016-02-26
          • 2019-08-23
          相关资源
          最近更新 更多