覆盖文件,但仅覆盖不是空格的部分 [英] Overwrite file, but only parts that are not spaces

查看:113
本文介绍了覆盖文件,但仅覆盖不是空格的部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种用00000覆盖.dat文件中某些部分的方法.为此,我有一个StringBuilder,其内容如下:

I am looking for a way to overwrite certain parts in a .dat file with 00000. For this I have a StringBuilder with content like this:

"00000000            0000000000000000          "

现在,我正在寻找一种方法,该方法用零覆盖文件中的各个部分,并用空格保留各个部分的内容.

Now I am looking for a method that overwrites the parts in the file with zeroes, and justs keeps the content of the parts with spaces.

如果我有

"AUEUIGHEVjerhvgm,eiouhegfwoedjkjjjjjjjjjjjjjjje" 

我希望它变成

"00000000Vjerhvgm,eio0000000000000000jjjjjjjjjje" 

是否存在这种方法?还是应该以另一种方式完成此任务?

Does such a method exist? Or should I accomplish this task in another way?

推荐答案

var byteCharZero = Convert.ToByte('0');
var stringBuilder = new StringBuilder("         00000000            0000000000000000 ");
using (var fileStream = File.Open("D:\\file.dat", FileMode.OpenOrCreate, FileAccess.Write))
{
  var length = Math.Min(stringBuilder.Length, fileStream.Length);
  for (var i = 0; i < length; i++)
  {
    if (stringBuilder[i] == '0')
    {
      fileStream.Position = i;
      fileStream.WriteByte(byteCharZero);
    }
  }
}

这篇关于覆盖文件,但仅覆盖不是空格的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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