Search code examples
c#openfiledialog

c# sorting a textfile


I have a question about how to sort a text file. I have a srec file and I need to sort it before I send it over COM1. So during opening or before sending I need to sort the file.

Here's a example of my srec file:

S2140338BE0E0606510004008D15FE915115FE9191CC S2140338CE04008D15FE9006010242C78C0AB79C04AF S2140338DE008D15FE91D6C78C0AB79C04088D1D0065 S2130338EE1A16270704088D1D001A0CC78C11190C
S20C038E880000000000000D23AA
S2100202C000033403000336C3000338DBDF S2140347C0045C3F0510060504008D15FEFC1304006B S2140347D08D15FEFD060104008D15FE80068304007C S2140347E08D15FE821304008D15FE8806FF04008DCA S2140347F015FE8906FF04008D15FE8E060104008D46

This is the source code:

StringList list = new StringList().FromFile(appfile.FileName);

        // Read file and put it in a list
        foreach (String line in list)
        {

            serialPort1.Write(line);
        }

        MessageBox.Show("Bootfile and Applicationfile are send succesfully.");

Solution

  • Though you could complicate it, if the file is of reasonable size (e.g. it's not a massive file) so it can be easily held in memory, it should be as simple as this:

    var lines = File.ReadAllLines("{PathToFile}");
    lines.Sort();
    File.WriteAllLines("{PathToFile}", lines);
    

    where {PathToFile} is the fully qualified physical path to your file.

    Here ReadAllLines returns a string[] and WriteAllLines writes back out a string[].

    Further, as proposed by Jim Mischel, another option would be something like this:

    File.WriteAllLines(filename, File.ReadLines(filename).OrderBy(s => s));
    

    The primary benefit of this approach is that the code is more elegant.