2012-02-01 198 views
1

我的项目中有一个名为“Images”的文件夹。我想获取Image文件夹的路径,以便我可以浏览并获取文件。获取文件夹相对路径的方法

我使用下面的一段代码来满足我上面的要求,它工作正常。

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); 

只是想知道像有没有这样做的优雅方式?获取文件夹路径的最佳方式是什么?

+0

这是无关的WPF – 2012-02-01 07:51:35

+0

您可以使用['Directory.GetParent'](http://msdn.microsoft.com/en-us/library/system.io .directory.getparent.aspx)来检索给定目录的父目录 – 2012-02-01 08:11:19

回答

4

这就是我通常使用:

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

注意它返回一个包含当前执行的代码的程序集的目录(我想这是你的主要可执行文件)。

为了让生成的路径的父目录,你也可以使用

Path.GetDirectoryName(appDirectory); 

我会建议对依赖于你的代码的Visual Studio项目结构,虽然。考虑将图像文件夹作为内容添加到应用程序中,以便它位于与可执行文件相同的目录中的子目录中。

1

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

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

1

你可以简单的使用Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)