获取文件夹的相对路径的方法

本文关键字:方法 路径 相对 获取 文件夹 | 更新日期: 2023-09-27 18:22:17

我的项目中有一个名为"Images"的文件夹。我想获取图像文件夹的路径,这样我就可以浏览并获取文件。

我正在使用下面的代码来满足我的上述需求,它运行得很好。

string basePath = AppDomain.CurrentDomain.BaseDirectory;
basePath = basePath.Replace("bin", "#");
string[] str = basePath.Split('#');
basePath = str[0];
string path = string.Format(@"{0}{1}", basePath, "Images");
string[] fileEntries = Directory.GetFiles(path);
  foreach (string fileName in fileEntries)
         listBox.Items.Add(fileName);

只是想知道有什么优雅的方法吗?获取文件夹路径的最佳方法是什么?

获取文件夹的相对路径的方法

这是我通常使用的:

string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

请注意,这将返回包含当前正在执行的代码的程序集的目录(我认为这是您的主要可执行文件)。

要获得结果路径的父目录,您也可以使用

Path.GetDirectoryName(appDirectory);

不过,我建议您不要在代码中依赖Visual Studio项目结构。考虑将images文件夹作为内容添加到应用程序中,使其与可执行文件位于同一目录中的子目录中。

如果您只是试图引用一个与另一个具有固定关系的目录,那么您可以使用相同的。。你会在命令行中使用的语法?

您还应该使用Path类中的方法(例如Path.Combine),而不是所有的字符串操作。