C#StreamWriter写入当前文本文件

时间:2014-10-29 05:42:44

标签: c# .net

我有一个文本文件,里面有以下文字:

[username][0]

我已使用StreamWriter打开文件,我想使用0方法将1更改为StreamWriter.Write。我怎么能这样做?

1 个答案:

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