[英]How to get the file relative path in c# service project?
我有以下代碼:
Stream stream = new StreamReader("~/quartz.xml").BaseStream;
Q1:C#中的“〜”符號指定路徑是什么?
Q2:如何在C#服務項目中獲取“〜”目錄?
Q3:這是否意味着bin exe目錄或項目名稱目錄?
我的Windows服務項目中的quartz.xml
文件位於兩個位置:
D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler\bin\Debug
D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler
確保路徑每次都會改變!因此獲得相對路徑更好。
完全忽略它:
Stream stream = new StreamReader("quartz.xml").BaseStream;
默認目錄是 .exe
的目錄。
根據OP對問題的編輯:
轉到查看 > 解決方案資源管理器 。 右鍵單擊有問題的文件,然后選擇“ 屬性” 。 將“ 復制到輸出目錄”選項更改為“始終復制” 。 然后使用上面的代碼。
如果我們使用(../quartz.xml):
StreamReader的讀取路徑是(不是文件實際路徑):
C:\Windows\quartz.xml
如果我們使用(quartz.xml):
StreamReader的讀取路徑是(不是文件實際路徑):
C:\Windows\system32\quartz.xml
這是查找文件相對路徑的方法:
string assemblyFilePath = Assembly.GetExecutingAssembly().Location;
string assemblyDirPath = Path.GetDirectoryName(assemblyFilePath);
string configFilePath = assemblyDirPath + "\\quartz.xml";
Stream stream = new StreamReader(configFilePath).BaseStream;
因此路徑為(您可以指定兩個)之一:
D:\jsptpd\Code\jsptpdJobScheduler\jsptpdJobScheduler\bin\Debug\quartz.xml
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.