簡體   English   中英

獲取文件夾相對路徑的方法

[英]Ways to get the relative path of a folder

我的項目中有一個名為“ 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);

只是想知道這樣做是否有任何優雅的方式? 獲取文件夾路徑的最佳方法是什么?

這是我通常使用的:

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

請注意,這將返回包含當前執行代碼的程序集的目錄(我假設這是您的主要可執行文件)。

要獲取結果路徑的父目錄,您還可以使用

Path.GetDirectoryName(appDirectory);

不過,我建議不要依賴於代碼中的Visual Studio項目結構。 考慮將images文件夾作為內容添加到您的應用程序,以便它位於與可執行文件相同目錄的子目錄中。

如果您只是嘗試引用與另一個目錄具有固定關系的目錄,那么您可以使用在命令行中使用的相同..語法?

您還應該使用Path類中的方法(例如Path.Combine),而不是所有的字符串操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM