我有一个文本文件,里面有以下文字:
[username][0]
我已使用StreamWriter打开文件,我想使用0
方法将1
更改为StreamWriter.Write
。我怎么能这样做?
答案 0 :(得分:1)
如果您知道要覆盖的字符的确切字节位置,那么您可以执行以下操作:
using (var writer = new StreamWriter(filePath))
{
writer.BaseStream.Seek(bytePos, SeekOrigin.Begin);
writer.Write('1');
}
如果您不知道确切的字节位置,那么您可以执行以下操作:
using (var file = new FileStream(filePath, FileMode.Open))
using (var reader = new StreamReader(file))
using (var writer = new StreamWriter(file))
{
var openBracketCount = 0;
// Keep reading characters until the second open bracket is found.
do
{
var ch = Convert.ToChar(reader.Read());
if (ch == '[')
{
openBracketCount++;
}
} while (openBracketCount < 2);
writer.Write('1');
}