-1

Suppose I have an array of strings with full file names and paths. For example

string[] filesArray = Directory.GetFiles(@"C:\dir", "*", SearchOption.AllDirectories);

Now let's say we have the following data in the array:

filesArray[0] = "C:\dir\file1.txt"
filesArray[1] = "C:\dir\subdir1\file2.txt"
filesArrat[2] = "C:\dir\subdir1\subdir2\file3.txt"
... etc.

Now I want a new array, that will store only the files' names, something like this:

nameArray[0] = "file1.txt"
nameArray[1] = "file2.txt"
nameArray[2] = "file3.txt"

What is the best way to do it, using string array only, without storing the full FileInfo class objects?

defcon1
  • 27
  • 5
  • 1
    use `Path.GetFileName`: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=net-6.0 – wohlstad May 04 '22 at 13:25

1 Answers1

2

Using LINQ it's pretty simple

string[] nameArray = filesArray.Select(p => Path.GetFileName(p)).ToArray()
user107511
  • 772
  • 3
  • 23