LordFlashheart
LordFlashheart

Reputation: 1

Ordering writeline outputs from text file using C# in console

I wonder if you could help me at all. Essentially my program has to scan through a text file and then print the lines. Each line that is printed must be alphabetized also, if possible. I could do with being able to point at any file through cmd rather than automatically pointing it at a specific file and in a specific location.

I have this so far as I wanted to get things working in a basic form.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Program
{
class Program
{
    static void Main(string[] args)
    {
        String line;
        try
        {
            //We Have to pass the file path and packages.txt filename to the StreamReader constructor
            StreamReader sr = new StreamReader("D:\\Users\\James\\Desktop\\packages.txt");

            //Instruction to read the first line of text
            line = sr.ReadLine();

            //Further Instruction is to to read until you reach end of file
            while (line != null)
            {
                //Instruction to write the line to console window
                Console.WriteLine(line);
                //The read the next line
                line = sr.ReadLine();
            }

            //Finally close the file
            sr.Close();
            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }
    }
}
}

I hope you guys can help me, I am very rusty!

My thoughts were to convert the string into an char array? then modify and sort using array.sort method.

OK guys. On your advice I have made a few changes. I get an exception thrown at me now as we are trying to get it to accept an argument in order for us to point it at any text file, not a specific one.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Program
{
class Program
{
    static void Main (params string[] args)
    {
        string PathToFile = args[1];
        string TargetPackages = args[2];

        try

        {

            string[] textLines = File.ReadAllLines(PathToFile);
            List<string> results = new List<string>();

            foreach (string line in textLines)
            {
                if (line.Contains(TargetPackages))
                {
                    results.Add(line);
                }

                Console.WriteLine(results);
            }
        }


        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
        finally
        {
            Console.WriteLine("Executing finally block.");
        }
    }
}
}

Upvotes: 0

Views: 832

Answers (2)

Jim Mischel
Jim Mischel

Reputation: 134085

If you just want to sort by the first word and output, you need to read all the lines into memory (I hope your file isn't too large), sort the lines, and then write them back out.

There are many ways to do all that. The File class has some helper functions that make reading and writing text files line-by-line very simple, and LINQ's OrderBy method makes quick work of sorting things.

File.WriteAllLines(
    outputFileName,
    File.ReadLines(inputFileName).OrderBy(line => line));

See File.WriteAllLines and File.ReadLines for information on how they work.

If you want to load each line, sort the first word, and then re-output the line:

File.WriteAllLines(
    outputFileName,
    File.ReadLines(inputFileName)
        .Select(line =>
            {
                var splits = line.Split(new [] {' '}};
                var firstWord = new string(splits[0].OrderBy(c => c));
                var newLine = firstWord + line.Substring(firstWord.Length);
                return newLine;
            }));

Note that this loads and processes one line at a time, so you don't have to hold the entire file in memory.

Upvotes: 1

Camilo Terevinto
Camilo Terevinto

Reputation: 32072

You should be better off by reading all lines at once and then looking at each line separately, like this:

List<string> allLines = System.IO.File.ReadLines(pathToFile).ToList();
allLines = allLines.OrderBy(line => line).ToList(); //this orders alphabetically all your lines
foreach (string line in allLines)
{
    Console.WriteLine(line);
}

This will print all the lines in the file ordered alphabetically.

You can also parametrize the path by using the args parameter you receive when opening the application:

CMD> pathToYourExe.exe path1 path2 path3

You can mock this by using the DEBUG arguments in the project's Debug menu

Upvotes: 0

Related Questions