Overwrite file, but only parts that are not spaces

a 夏天 提交于 2019-12-13 06:23:45

问题


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.

So if I have

"AUEUIGHEVjerhvgm,eiouhegfwoedjkjjjjjjjjjjjjjjje" 

I want it to turn into

"00000000Vjerhvgm,eio0000000000000000jjjjjjjjjje" 

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


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



回答2:


I think your specification is slightly in error, but it seems that you want something like this:

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

In this example, result will be 000000000jerhvgm,000000000000jkjjjjjjjjjjjjjj0e which isn't what your example states - but I think your example is slightly wrong...



来源:https://stackoverflow.com/questions/21577249/overwrite-file-but-only-parts-that-are-not-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!