问题
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