0

enter image description hereUsing C# How to change the particular character (based on position ) in particular line in .txt file?

shibin km
  • 3
  • 2

1 Answers1

0

If you know the line index you can use:

// Get file content as string array.
var lines = File.ReadAllLines(filePath);

var sb = new StringBuilder(lines[lineIndex]);

// Replacing character at given position
sb[CharacterIndex] = 'A';

lines[lineIndex] = sb.ToString();

// Writing new content to file
File.WriteAllLines(filePath, lines);

Update (based on new question details)

Your question is about change particolar string (not character) based on position in particular line. Your function could be:

void replaceStringAtPosition(string filePath, int lineNumber, int StartingCharacterPosition, int replaceWordLength, string replaceWord)
{
    // Get file content as string array.
    var lines = File.ReadAllLines(filePath);

    var sb = new StringBuilder(lines[lineNumber]);

    if (StartingCharacterPosition > sb.Length - 1) throw new Exception(nameof(StartingCharacterPosition) + " parameter value is greater than line length");

    int numberOfCharactersToRemove = StartingCharacterPosition + replaceWordLength > sb.Length - 1 ? sb.Length - StartingCharacterPosition : replaceWordLength;

    // Replacing string at given position
    sb.Remove(StartingCharacterPosition, numberOfCharactersToRemove);
    sb.Insert(StartingCharacterPosition, replaceWord);

    lines[lineNumber] = sb.ToString();

    // Writing new content to file
    File.WriteAllLines(filePath, lines);
}

See this answer too.

Omar Muscatello
  • 1,256
  • 14
  • 25
  • these are the parameters which i have (string filePath, int lineNumber,int StartingCharacterPosition, Int replaceWordLength, string replaceWord) – shibin km Aug 02 '17 at 06:37