E
E
Envywewok2019-05-11 15:04:30
C++ / C#
Envywewok, 2019-05-11 15:04:30

How to get the names of all files in a folder?

I'm writing here until I've done something as ugly as possible). You need to get the names of all the files in the folder, so that later they can be parsed and searched for what you need.
I tried this and thought I was close to success:

var test = "..."; // тут путь к папке
 string[] test1 = Directory.GetFiles(test);

But I didn't get names, but full paths to files + filenames.
I went to try to get only names, I succeeded. But the code looks terrible. I don't know how to fix it.
var test = "C:/Users/Hristoforov/hgtwithourarch/Belarus";
            DirectoryInfo di = new DirectoryInfo(test);
            string[] test1 = new string[Directory.GetFiles(test).Length];
            int i = 0;
            foreach (var s in di.GetFiles())
            {
                test1[i] = s.Name;
                i++;
            }

In general, the task is to split the file name into variables and, based on this data, decide whether the file is suitable or not. If there is no option to get all the names at once into an array of strings, then, probably, there is no point in creating another structure, and when iterating (through foreach), immediately carry out all the actions I need.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
#
#, 2019-05-11
@Envywewok

1 - var fnOnly = Path.GetFileName(fullPath)
2 -

var files = Directory.GetFiles(@"c:\").Select(fn => Path.GetFileName(fn));
it will be IEnumerable
3 - if we can’t work with anything other than arrays, well, something like this
var files = Directory.GetFiles(@"c:\").Select(fn => Path.GetFileName(fn)).ToArray();

R
Ronald McDonald, 2019-05-11
@Zoominger

Use GetFileName (String) :
https://docs.microsoft.com/en-us/dotnet/api/system...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question