GetFiles () does not return the first file name in a C # directory

I am writing a test script for use in a larger script. I need to get the very first file in the Music Directory so that I can automate opening wmplayer and playing the first song.

If I hardcode the file name and start the process, it works. However, if someone wants to use a script, I need to get the first file name. For example, my hard-coded version:

Process.Start("wmplayer.exe", "C:\\Users\\" + username + "\\Music\\A_ChillstepMix.mp3");

When I try to get the first file in the Music folder in my test script, it returns it in the picture:

Incorrect file access

what is wrong! What am I doing wrong? Here is my snippet:

using System;
using System.IO;
using System.Linq;

namespace GetFileTest
{
    class Program
    {
        static void Main(string[] args)
        {
            String username = Environment.UserName;
            String path = @"C:\Users\" + username + @"\Music";
            DirectoryInfo di = new DirectoryInfo(path);
            string firstFile = di.GetFiles().Select(fi => fi.Name).FirstOrDefault();

            Console.WriteLine(firstFile);            
        }        
    }
}

I also tried:

string firstFile = di.GetFiles()[0].ToString();

to no avail. Does this have anything to do with single quotes?

+4
source share
1 answer

You must sort the file names before choosing the first option:

di.GetFiles().OrderBy(fi => fi.Name).Select(fi => fi.Name).FirstOrDefault();
+4
source

Source: https://habr.com/ru/post/1687098/


All Articles