4

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

If I hard code the file name and start the Process, it works. However, if someone else wants to use the script, I need to get the first file name. For example, my hard coded version is:

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 is returning the one in the picture:

Wrong File Being Accessed

which isn't the correct one! 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 have also tried:

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

to no avail. Does it have something to do with the single quotes?

DevOpsSauce
  • 1,319
  • 1
  • 20
  • 52

1 Answers1

4

You have to sort the file names before you select the first one as:

di.GetFiles().OrderBy(fi => fi.Name).Select(fi => fi.Name).FirstOrDefault();
Hussein Salman
  • 7,806
  • 15
  • 60
  • 98