0

So, I want to write the file names of a certain directory to a text file. For my program I only need the file names, not the full path. I already put them in an array like so:

 string[] charDir = Directory.GetFiles(SettingsInit.Default.GameDir + @"\stages", "*.def", SearchOption.TopDirectoryOnly);

The output of Directory.GetFiles() are the full paths, e.g.:

C:\Users\%username%\Desktop\mugen_1.1\stages\radicalHighway.def

How can I remove the path from each item, so that I only get the file name? I thought about iterating through each item, but I don't know how to achieve this properly. Since I'd always write charDir[charDir.ToString().IndexOf(i)] in the foreach loop, I'm not sure if it would work this way.

  • You could use `FileInfo.Name` – zc246 Dec 29 '17 at 13:46
  • One possible way: `string[] charDir = new DirectoryInfo(Path.Combine(SettingsInit.Default.GameDir, "stages")).GetFiles("*.def").Select(f => f.Name).ToArray();` – Jimi Dec 29 '17 at 14:01

1 Answers1

3

System.IO.Path is a really nice namespace. Try the System.IO.Path.GetFileName function to get only the file name.

I also really like System.IO.Path.Combine, great feature.

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
Ctznkane525
  • 7,297
  • 3
  • 16
  • 40
  • 1
    yes ! don't do things like `SettingsInit.Default.GameDir + @"\stages"` but use `Path.Combine()` instead. – Pac0 Dec 29 '17 at 13:47
  • 1
    You surely mean `Path.GetFileName()` (like you linked), not `Path.Combine`. And link only answers are discouraged on SO. Please add some explanation or a little code example. – René Vogt Dec 29 '17 at 13:48
  • I said I ALSO really like the other function. As in, I also use that one a lot. – Ctznkane525 Dec 29 '17 at 13:49