none
How to append text file from the top? RRS feed

  • Question

  • My program creates a log file which it appends from the bottom:

    File.AppendAllText ();

    Well, I want it to do it in reverse, to append new lines from the top in such a way that the newest line will appear on top of the file, not the bottom. Can I do it? Microsoft does it all the time.

    Thanks, - Alex

    Tuesday, June 12, 2018 1:08 AM

Answers

  • My program creates a log file which it appends from the bottom:

    File.AppendAllText ();

    Well, I want it to do it in reverse, to append new lines from the top in such a way that the newest line will appear on top of the file, not the bottom. 

    A note about terminology: "appending" refers to adding something to the
    end. The correct term for adding/inserting at the start is "prepending".

    I'm not nit-picking, just alerting you to that distinction as it may
    help you if you do a web search for answers, solutions or examples.

    Often the easiest way to do this is to read all lines from the file into a 
    list, insert the new line at the start of the list, then write all lines
    from the list to the file.

    The ability to insert directly at the start or at an arbitrary location
    in a file usually requires that the file be managed by a database library.

    - Wayne

    • Marked as answer by MyCatAlex Tuesday, June 12, 2018 10:27 AM
    Tuesday, June 12, 2018 2:20 AM

All replies

  • My program creates a log file which it appends from the bottom:

    File.AppendAllText ();

    Well, I want it to do it in reverse, to append new lines from the top in such a way that the newest line will appear on top of the file, not the bottom. 

    A note about terminology: "appending" refers to adding something to the
    end. The correct term for adding/inserting at the start is "prepending".

    I'm not nit-picking, just alerting you to that distinction as it may
    help you if you do a web search for answers, solutions or examples.

    Often the easiest way to do this is to read all lines from the file into a 
    list, insert the new line at the start of the list, then write all lines
    from the list to the file.

    The ability to insert directly at the start or at an arbitrary location
    in a file usually requires that the file be managed by a database library.

    - Wayne

    • Marked as answer by MyCatAlex Tuesday, June 12, 2018 10:27 AM
    Tuesday, June 12, 2018 2:20 AM
  • Understood. Thanks.
    Tuesday, June 12, 2018 10:27 AM