我正在尝试使用位于特定路径中的所有文件创建一个下拉菜单,问题是当我加载文件时,该下拉菜单中的显示带有完整路径作为其名称,我如何更改此文件并仅保留文件名称显示在下拉菜单中? 我该如何解决?
void loadedfiles()
{
string[] myload = getfilesname();
}
string[] getfilesname()
{
string folderPath = Path.Combine(Application.persistentDataPath, foldername);
string[] filePaths = Directory.GetFiles(folderPath, "*.txt");
foreach (string file in filePaths)
{
mylist.Add(file);
Debug.Log(file);
}
dropi.AddOptions(mylist);
return filePaths;
}
答案 0 :(得分:0)
Youc可以使用Path.GetFileName(string path)
(或Path.GetFileNameWithoutExtension(string path)
)从给定的路径字符串中仅获取文件名部分。
string[] filePaths = Directory.GetFiles(folderPath, "*.txt");
foreach (string file in filePaths)
{
var onlyFileName = Path.GetFileName(file);
mylist.Add(onlyFileName);
Debug.Log(onlyFileName);
}
作为替代方案,但可能不是最佳/最清洁的解决方案
string[] filePaths = Directory.GetFiles(folderPath, "*.txt");
foreach (string file in filePaths)
{
// split the path into all parts on the seperators (/ or \)
var pathParts = file.Split(Path.DirectorySeparatorChar);
// take only the last part which should be the filename
var onlyFileName = pathParts[pathParts.Length - 1];
mylist.Add(onlyFileName);
Debug.Log(onlyFileName);
}