Suppose we have 3 text files that will be called, for example, one.txt, two.txt, and three.txt. The number 100 is written in the file one.txt. In the file two.txt - 15. And in three.txt - 60 How can I display the names of these files (along with .txt) and their contents in this format:

one.txt - 100 two.txt - 15 three.txt - 60 

I found the code, but it displays only the contents of the files, I just can’t make it so that along with this content the name of the file in which it is displayed

 var fileStorage = new List<string[]>(); string path = @"..." string[] promoDir = Directory.GetFiles(path); try { var filePaths = Directory.GetFiles(path); //string[] foreach (string path in filePaths) { string[] fileLines = System.IO.File.ReadAllLines(path); fileStorage.Add(fileLines); } foreach (string[] fileLines in fileStorage) { foreach (string fileLine in fileLines) { Console.WriteLine(); } } 

Thank you in advance!

    1 answer 1

    The most elementary:

     var result = Directory.GetFiles("temp") .Select(x => new { Name = Path.GetFileName(x), Value = File.ReadAllText(x) }); 

    Conclusion:

     foreach (var file in result) Console.WriteLine($"{file.Name} - {file.Value}"); 

    Explanations:

    • Directory.GetFiles("temp") - Get the files in the specified directory (in my case it is temp , which lies next to the project .exe file).
    • .Select() is one of the LINQ extensions that each element of the collection translates into the type we need. In my case, this is an anonymous type with two values ​​( Name and Value ).
    • Name = Path.GetFileName(x) - In Name we put the name of the file with the extension (if necessary without it, we use Path.GetFileNameWithoutExtension() ).
    • Value = File.ReadAllText(x) - in the Value place all the text from the file.

    Here you can play as you like, for example, we make a String at once with the desired look:

     var result = Directory.GetFiles("temp") .Select(x => $"{Path.GetFileName(x)} - {File.ReadAllText(x)}" ); 

    Here already see for yourself what you need.


    Option without LINQ:

     foreach (var file in Directory.GetFiles("temp")) Console.WriteLine($"{Path.GetFileName(file)} - {File.ReadAllText(file)}"); 

    What is it and how I think you guessed it.

    • Thanks, helped! It turns out everything was so simple) - Shellar