簡體   English   中英

獲取文件的相對路徑?

[英]Getting relative path of file?

我有一個名為settings.xml的文件,位於:

c:\\solution1\\solution1\\data\\settings.xml

現在,我正在做:

XDocument doc = XDocument.Load(@"c:\solution1\solution1\settings.xml");

我不知道如何使用相對路徑。

如果您的意思是相對於可執行文件,則可以使用

string exeLocation = System.Reflection.Assembly.GetExecutingAssembly().CodeBase

注意經常建議

System.Reflection.Assembly.GetExecutingAssembly().Location

將獲取程序集當前所在的路徑,該路徑可以不同,例如,如果正在執行卷影副本。

您可以使用

string exeDir = System.IO.Path.GetDirectoryName(exeLocation);

獲取可執行文件的目錄。

如果要在安裝位置下的數據目錄中找到文件,可以執行

string dataFile = Path.Combine(exeDir, "data\settings.xml");

需要注意的是在Windows Vista和更高版本,你不會有默認的寫訪問位於你的安裝目錄下的目錄。

您還可以相對於它從其開始的當前目錄

System.Environment.CurrentDirectory

暫無
暫無

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

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