0

I've been trying to make a program that asks you the path and searches for any text files present there and outputs it, but it doesn't work

here is my code:

            Console.WriteLine("What is the path?");
            string path = Console.ReadLine();
            string[] files = System.IO.Directory.GetFiles(path,"*.txt");
            Console.WriteLine(files);

This code however prints System.String[] instead of the files name

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Techy Shadow
  • 354
  • 3
  • 13

2 Answers2

2

You need to iterate the files array. You can use foreach loop for printing file names.

Console.WriteLine("What is the path?");
string path = Console.ReadLine();
string[] files = System.IO.Directory.GetFiles(path, "*.txt");        
foreach (string file in files)
{
    Console.WriteLine(file);
}

If you want to get the file name only, then use as :

Console.WriteLine(Path.GetFileName(file));

If you want to get the file name without extension, then use as :

Console.WriteLine(Path.GetFileNameWithoutExtension(file));
Mohammad Arshad Alam
  • 9,694
  • 6
  • 38
  • 61
0

If you look at this line in your code

string[] files = System.IO.Directory.GetFiles(path,"*.txt");

You see that the call to GetFiles returns System.String[], hence the reason why this is output.

So you need to iterate the array and output the details to the console. A Foreach is one method.

foreach(string file in System.IO.Directory.GetFiles(path,"*.txt"))
     Console.WriteLine(file);

I would also suggest in your program that you should put some additional checks, to ensure that the input entered by the user is valid, before you try calling GetFiles. This will help to avoid problems and exceptions occurring.

jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51
  • So I can use a if statement to make sure that the input is not null and then continue the rest? – Techy Shadow Aug 25 '21 at 04:52
  • 1
    Yes, use String.IsNullOrWhiteSpace to check for null or empty string, also use System.IO.Directory.Exists to check that the directory exists before trying to iterate it, which will also help in case there is an access rights problem. – jason.kaisersmith Aug 25 '21 at 05:04