覆盖文件,但只覆盖非空格的部分

时间:2014-02-05 12:25:14

标签: c# stringbuilder streamwriter overwrite

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

"00000000            0000000000000000          "

现在我正在寻找一种方法,用零覆盖文件中的部分,而justs用空格保留部分的内容。

所以,如果我有

"AUEUIGHEVjerhvgm,eiouhegfwoedjkjjjjjjjjjjjjjjje" 

我希望它变成

"00000000Vjerhvgm,eio0000000000000000jjjjjjjjjje" 

这种方法存在吗?或者我应该以另一种方式完成这项任务?

2 个答案:

答案 0 :(得分:1)

我认为你的规范有点错误,但似乎你想要这样的东西:

var pattern   = new StringBuilder("         00000000            0000000000000000 ");
var target    = "AUEUIGHEVjerhvgm,eiouhegfwoedjkjjjjjjjjjjjjjjje";
var workspace = new StringBuilder(target);

for (int i = 0, n = Math.Min(pattern.Length, target.Length); i < n; ++i)
    if (pattern[i] != '0')
        workspace[i] = '0';

string result = workspace.ToString();

在这个例子中,结果将是000000000jerhvgm,000000000000jkjjjjjjjjjjjjjj0e,这不是你的例子所说的 - 但我认为你的例子有点错误......

答案 1 :(得分:1)

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);
    }
  }
}