Return name of file only

I’m having an issue with reading only the name of the file that I want, not the entire directory.

Here are the relevant lines of code:

files = Directory.GetFiles(Application.dataPath + "/Levels/");
...
for (var file : String in files)

I want file to be the name of the file.

I’m sure the answer is a simple one, but I haven’t been able to find one, despite searching and my own attempts.

Thanks

1 Answer

1

use Path.GetFileName.

Use String.Split with a period as the separator, and select the first element in the string[] it returns. That should be the filename while the second element is the extension. See: http://msdn.microsoft.com/en-us/library/b873y76a.aspx

NO! Use system tools, do not build your own bycicles! Use Path.GetFileNameWithoutExtension

Sure, that would probably be better, since it allows you to have periods in the filename. While systems tool are easier where available, constructing your own in simple cases like this one isn't a complete catastrophy, though...

You wouldn't use Split anyway even if GetFileNameWithoutExtension didn't exist, since file names like "blah.123XYZ.txt" are legal. Instead you would use LastIndexOf and Substring.