- Home /
How Do I Find Path of a File?
I'm trying to make a system that looks in a directory to find files of a certain type and load them onto a display. In my code, I had already found the files, but I want to do the reading and loading of the file in another method:
void GetWorlds () {
if (Directory.Exists(Application.DataPath + "\Worlds")) {
string worldsFolder = Application.DataPath + "\Worlds";
DirectoryInfo d = new DirectoryInfo(worldsFolder);
foreach (var file in d.GetFiles("*.cubes"))
{
DisplayWorldData(file.);
}
} else {
File.Create(Application.DataPath + "\Worlds");
return;
}
}
I don't quite know how to find the location of the file already specified to be able to send its information to the other method "DisplayWorldData". Help please!
Answer by Kudorado · Dec 26, 2018 at 03:17 AM
var directoryPath = Application.DataPath + "\Worlds";
foreach (var file in d.GetFiles("*.cubes"))
{
var path = file;
var fileName = path.Replace(directoryPath, string.Empty);
DisplayWorldData(fileName);
}
you can check references GetFiles here: https://docs.microsoft.com/en-us/dotnet/api/system.io.directory.getfiles?view=netframework-4.7.2
Hello, thank you for answering! The system no longer throws errors at me, which is good, but I tried to make a Debug.Log to tell me the file path and it never shows! I'm fairly sure my folders and files are correctly placed. I modified the code a little bit since last time: public void GetWorlds () { if (Directory.Exists(Application.dataPath + "WorldFolder")) { string worldsFolder = Application.dataPath + "WorldFolder";
string[] cubesFiles = Directory.GetFiles(worldsFolder, "*.cubes");
foreach (var cubesFile in cubesFiles)
{
DisplayWorldData(cubesFile);
}
} else {
File.Create(Application.dataPath + "WorldFolder");
return;
}
}
public void DisplayWorldData (string filePath) {
Debug.Log("Found world with directory of: " + filePath);
}
Try Replace
` if (Directory.Exists(Application.dataPath + "WorldFolder")) { string worldsFolder = Application.dataPath + "WorldFolder";`
To
` if (Directory.Exists(Application.dataPath + "/WorldFolder")) { string worldsFolder = Application.dataPath + "/WorldFolder";`
Your answer
Follow this Question
Related Questions
Add files to folder 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
File.Move wont work , error. IOException: Win32 IO returned ERROR_ALREADY_EXISTS. Path: 1 Answer
Will System.IO.File work on Macs 2 Answers