문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top