- Home /
C# Getting only the Name of the XML File and not the Directory of the XML File
Hi everyone, is there a way to get only the name of an xml file and not the directory of the file? I declared public string[] XMLfiles = Directory.GetFiles(Application.dataPath,"*.XML"); which does list the XML files but it doesn't get the names of the files . In the elements it lists where the XML files are located within the project but I want the names only. Is there a way to do that?
Answer by stfx · Dec 28, 2012 at 08:10 PM
When you have a string of the full path (which you get from Directory.GetFiles) you can use the .NET method System.IO.Path.GetFileName(fullPath) to get the file name plus extension.
// GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext'
// GetFileName('C:\mydir\') returns ''
Is there a way to get the file name without referencing it directly? Like with for loops. Example
public string[] X$$anonymous$$Lfiles = Directory.GetFiles(Application.dataPath,"*.X$$anonymous$$L");
public string ExampleString;
void OnGUI(){
for(int a = 0; a < X$$anonymous$$Lfiles.Length; ++a){
if(GUILayout.Button("ExampleButton")){
ExampleString = X$$anonymous$$Lfiles[a];
}
}
}
What exactly would I need to change in the above code to do that?
Of course:
ExampleString = System.IO.Path.GetFileName(X$$anonymous$$Lfiles[a]);
And if you don't want he extension and only your file name you can use this : http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension.aspx
the function : GetFileNameWithoutExtension( string path )
Answer by Geo.Ego · Dec 28, 2012 at 10:10 PM
Use System.IO.Path.GetFileName after getting your string array.
public string[] XMLfiles = Directory.GetFiles(Application.dataPath,"*.XML");
foreach(string file in XMLfiles)
{
print(Path.GetFileName(file));
}
Of course, you'll need to modify that to do what you want with each file name.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
JSON vs XML for Unity C# 1 Answer
Best practice to store and load a specific set of objects? 3 Answers
Creating a save.xml file and a folder to stash it in 1 Answer