Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get file names without path or extension and output to a list.

Tags:

c#

Was given this by a coworker but I need just file names:

    private List<string> getWavFileList()
    {
        string path = @"c\test automation\wave files";

        string[] files = Directory.GetFiles(path, "*.wav");


        List<string> list = new List<string>(files);

        return list;

    }

The output list contains the path and extension and I need the file name only. I was working on my own method but can't get it to compile:

    private List<string> getWavFileList()
    {
        StringBuilder builder = new StringBuilder();
        string path = @"c\test automation\wave files";
        DirectoryInfo di = new DirectoryInfo(path);
        FileInfo[] smFiles = di.GetFiles("*.wav");
            foreach (FileInfo fi in smFiles)
            {
                builder.Append(Path.GetFileNameWithoutExtension(fi.Name));
                builder.Append(", ");
            }

            string files = builder.ToString();

            List list = new List<string>(files);

            return list;
like image 806
Larvaman Avatar asked Mar 09 '23 00:03

Larvaman


1 Answers

I'd suggest modifying to something like the following;

private List<string> getWavFileList()
{
    string path = @"c:\test automation\wave files";
    DirectoryInfo di = new DirectoryInfo(path);
    FileInfo[] smFiles = di.GetFiles("*.wav");
    List<string> list = new List<string>(smFiles.Select(f => Path.GetFileNameWithoutExtension(f.Name)));

    return list;
}
like image 103
DiskJunky Avatar answered Apr 06 '23 11:04

DiskJunky