C#读取并替换文本文件中的二进制数据 [英] C# Read and replace binary data in text file

查看:38
本文介绍了C#读取并替换文本文件中的二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含文本数据和二进制数据的文件.这可能不是一个好主意,但是对此我无能为力.我知道二进制数据的结束位置和开始位置.

I have a file that contains text data and binary data. This may not be a good idea, but there's nothing I can do about it. I know the end and start positions of the binary data.

最好的方法是在这些位置之间读取二进制数据,从中取出Base64字符串,然后将其写回到原来的位置.

What would be the best way to read in that binary data between those positions, make a Base64 string out of it, and then write it back to the position it was.

Base64编码的字符串与二进制数据的长度将不同,因此我可能不得不将Base64字符串填充为二进制数据的长度.

The Base64-encoded string won't be same length as the binary data, so I might have to pad the Base64 string to the binary data length.

推荐答案

int binaryStart = 100;
int binaryEnd = 150;

//buffer to copy the remaining data to it and insert it after inserting the base64string
byte[] dataTailBuffer = null;

string base64String = null;

//get the binary data and convert it to base64string
using (System.IO.Stream fileStream = new FileStream(@"c:\Test Soap", FileMode.Open, FileAccess.Read))
{
    using (System.IO.BinaryReader reader = new BinaryReader(fileStream))
    {
        reader.BaseStream.Seek(binaryStart, SeekOrigin.Begin);

        var buffer = new byte[binaryEnd - binaryStart];

        reader.Read(buffer, 0, buffer.Length);

        base64String = Convert.ToBase64String(buffer);

        if (reader.BaseStream.Position < reader.BaseStream.Length - 1)
        {
            dataTailBuffer = new byte[reader.BaseStream.Length - reader.BaseStream.Position];

            reader.Read(dataTailBuffer, 0, dataTailBuffer.Length);
        }
    }
}

//write the new base64string at specifid location.
using (System.IO.Stream fileStream = new FileStream(@"C:\test soap", FileMode.Open, FileAccess.Write))
{
    using (System.IO.BinaryWriter writer = new BinaryWriter(fileStream))
    {
        writer.Seek(binaryStart, SeekOrigin.Begin);

        writer.Write(base64String);//writer.Write(Convert.FromBase64String(base64String));

        if (dataTailBuffer != null)
        {
            writer.Write(dataTailBuffer, 0, dataTailBuffer.Length);
        }
    }
}

这篇关于C#读取并替换文本文件中的二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆