Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取文件夹相对路径的方法_C# - Fatal编程技术网

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

C# 获取文件夹相对路径的方法,c#,C#,我的项目中有一个名为“Images”的文件夹。我想获取图像文件夹的路径,以便浏览该文件夹并获取文件 我正在使用下面的代码来满足我的上述要求,它运行良好 string basePath = AppDomain.CurrentDomain.BaseDirectory; basePath = basePath.Replace("bin", "#"); string[] str = basePath.Split('#'); basePath = str[0]; string path = string.

我的项目中有一个名为“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);

我只是想知道有没有什么优雅的方法可以做到这一点?获取文件夹路径的最佳方法是什么?

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


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

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


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

这是我通常使用的:

string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
请注意,这将返回包含当前正在执行的代码的程序集目录(我假设这是您的主要可执行文件)

要获取结果路径的父目录,还可以使用

Path.GetDirectoryName(appDirectory);

不过,我建议不要依赖代码中的VisualStudio项目结构。考虑将图像文件夹作为内容添加到应用程序中,使其驻留在与可执行文件相同的目录中的子目录中。p> 这是我通常使用的:

string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
请注意,这将返回包含当前正在执行的代码的程序集目录(我假设这是您的主要可执行文件)

要获取结果路径的父目录,还可以使用

Path.GetDirectoryName(appDirectory);

不过,我建议不要依赖代码中的VisualStudio项目结构。考虑将图像文件夹作为内容添加到应用程序中,使其驻留在与可执行文件相同的目录中的子目录中。p> 这与wpfYou可用于检索给定目录的父目录无关这与wpfYou可用于检索给定目录的父目录无关