0

I have a simple Question to ask, how to use Seek() method in C# to write at the specific position in the Txt file. Example:

InfoBrother.    //this is the Name.

and I want to append - like.

Info-Brother    //just want to add (-) after "o" in the Name.

Thanks in Advance.

Abhishek
  • 2,925
  • 4
  • 34
  • 59
  • show your code.. – Abhishek Jun 29 '17 at 04:35
  • @Abhishek i am trying to write a code, i can append the file at the end, but how to do it in the middle of the text ? can you write the simple code for it. ? – InfoBrother Jun 29 '17 at 04:38
  • Please see [FileStream.Seek Method](https://msdn.microsoft.com/en-us/library/system.io.filestream.seek(v=vs.110).aspx) article on MSDN. If you need a debugging help, you have to include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. See also [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) post. – Alexander Jun 29 '17 at 05:05

1 Answers1

0

If you seek to the position of 'o' and start writing from there, then the number of bytes you write, those many number of characters after 'o' will be overwritten.

Assuming that your text file name is "a.txt", the following is a better way:

string[] lines = File.ReadAllLines("a.txt");
for(int i = 0; i<lines.Length; i++)
{
    if(lines[i].Contains("InfoBrother"))
    {
        lines[i] = lines[i].Insert(4, "-");
    }
}
File.WriteAllLines("a.txt", lines);

If you still want to seek and write, then the best answer is in this CodeProject article

Abhishek
  • 2,925
  • 4
  • 34
  • 59