3

I have a list of text files that I want to be able to open in a console application.

The output I want is something like:

  1. List1.txt
  2. List2.txt
  3. List3.txt

    etc

Once I get this output I want a way of being able to call one of those files and have it open via Console.ReadLine();

What I'm doing at the moment is

string[] FileNames = Directory.GetFiles(@"Itemized\", ".txt");
Console.WriteLine(String.Join(Environment.NewLine,FileNames));    

This allows me to get as far as getting list that looks like:

Itemized\List1.txt

Itemized\List2.txt

Itemized\List3.txt

If I know the number of files in the folder I can hard code it but the problem I have is that any number of files could be present.

So what im looking for at the moment is a way to append a scaling numeric value to each file and remove the folder-name from the front of it.

I've tried using a for loop to get it to work but can't seem to get my head around it.

2 Answers 2

3

Try something like this

var fileNames = Directory.GetFiles(@"Itemized\", "*.txt").Select(Path.GetFileName).ToArray();
Console.WriteLine(string.Join(Environment.NewLine, fileNames));
3
  • Only works if I remove "*.txt" any idea why ? Everything displays as text documents and when i remove it the list forms without them. Either way you helped me get closer to what i want have an upvote
    – Spooler
    Jul 8, 2016 at 5:24
  • @Spooler for me it works fine. The only problem in my example is that you didn't get any line numbers. To reach this your have to output the fileNames using an for loop like @Ephraim used it Jul 8, 2016 at 5:28
  • Yea that's why he got the accepted answer, ( having shown the for loop to add the value). Anyways now it's time for me to figure out how to provide user interaction for this menu
    – Spooler
    Jul 8, 2016 at 5:35
2

Here is something clean and simple:

    static void Main(string[] args)
    {
        string dirFolderPath = string.Format("{0}/{1}", Directory.GetCurrentDirectory(), "Itemized");
        DirectoryInfo dir = new DirectoryInfo(dirFolderPath);

        if(!dir.Exists)
        {
            dir.Create();
        }

        FileInfo[] files = dir.GetFiles("*.txt");

        for(int i = 0; i < files.Length; i++)
        {
            string line = string.Format("\n{0}-{1}", i, files[i].Name);
            Console.WriteLine(line);   
        }

        Console.ReadLine();
    }
2
  • This looks amazing testing it out
    – Spooler
    Jul 8, 2016 at 5:24
  • This is EXACTLY what I was looking for! Thank you so much :)
    – Spooler
    Jul 8, 2016 at 5:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.