Replace whole line of Text from textfile

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jetean
    New Member
    • Feb 2008
    • 33

    Replace whole line of Text from textfile

    Hi:
    If I have text as below in a Text file "Sample.txt ":

    <STX>jjjjjjjjjj jjjjjjjjjjjjjjj jj<ETX>
    <STX>hhhhhhhhhh hhhhhhhh<ETX>
    <STX>6666666666 66666666666666< ETX>
    <STX>9999999999 99999999999999< ETX>
    <STX>11111<ET X>
    <STX>333333<ETX >
    <STX>kkkk<ETX >
    <STX>555555<ETX >


    How do I Replace line no 5 or any specific line with a new string/text?
  • Curtis Rutland
    Recognized Expert Specialist
    • Apr 2008
    • 3264

    #2
    Read the whole file into a string. Then, you can .Split it around a newline character ( '\n' in c#, not sure about VB). .Split returns an array. So if you want to replace line 5, you would change stringArray[4] to whatever you want. Remember that arrays are zero based.

    Then, loop through your array, concatenating all your strings into one string with newlines after each one, and overwrite it back to the text file. Pretty simple, really.

    We have a howto on reading/writing a text file in C#. The theory is no different in VB, just the syntax. You can also google String.Split if you need more information on how to do that.

    Comment

    Working...