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

This is given by a colleague, but I only need the 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 only need the file name. I worked on my own method, but I can not compile it:

    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;
+4
source share
3 answers

I would suggest changing 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;
}
+3
source

In the first solution, replace this line

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

with this:

return files.Select(Path.GetFileNameWithoutExtension).ToList();

This requires use System.Linq.

+2
source

I don't know why you concatenate the lines with a comma, I thought you needed a list:

private List<string> getWavFileList()
{
    return Directory.EnumerateFiles(@"c\test automation\wave files", "*.wav")
        .Select(System.IO.Path.GetFileNameWithoutExtension)
        .ToList();
}
+2
source

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


All Articles