C# 在一个文件指定位置后面插入字节,如在100位置后面插入 0x01,0x02这两个字节

首次发布:2025-05-31
using System;
using System.IO;

class FileByteInsertion
{
    static void Main(string[] args)
    {
        string sourceFilePath = "source.pdf";  // 源文件路径
        string outputFilePath = "output.pdf";  // 输出文件路径
        int insertionPosition = 100;           // 插入位置(第100字节后)
        byte[] bytesToInsert = { 0x01, 0x02 }; // 要插入的字节

        try
        {
            InsertBytesAtPosition(sourceFilePath, outputFilePath, insertionPosition, bytesToInsert);
            Console.WriteLine("字节插入成功!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"操作失败:{ex.Message}");
        }
    }

    static void InsertBytesAtPosition(string sourcePath, string outputPath, int position, byte[] bytesToInsert)
    {
        // 验证输入参数
        if (!File.Exists(sourcePath))
        {
            throw new FileNotFoundException("源文件不存在!", sourcePath);
        }

        if (position < 0)
        {
            throw new ArgumentException("插入位置不能为负数!", nameof(position));
        }

        // 获取源文件长度
        long fileLength = new FileInfo(sourcePath).Length;

        // 检查插入位置是否超出文件长度
        if (position > fileLength)
        {
            Console.WriteLine($"警告:插入位置({position})超出文件长度({fileLength}),将在文件末尾添加字节。");
            position = (int)fileLength;
        }

        using (FileStream sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
        using (FileStream outputStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            // 复制前position个字节
            long bytesCopied = 0;
            while (bytesCopied < position)
            {
                int bytesToRead = (int)Math.Min(buffer.Length, position - bytesCopied);
                bytesRead = sourceStream.Read(buffer, 0, bytesToRead);
                if (bytesRead == 0) break;
                outputStream.Write(buffer, 0, bytesRead);
                bytesCopied += bytesRead;
            }

            // 插入新字节
            outputStream.Write(bytesToInsert, 0, bytesToInsert.Length);

            // 复制剩余的字节
            while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                outputStream.Write(buffer, 0, bytesRead);
            }
        }
    }
}

本文来自 www.luofenming.com