2011-09-01 23 views
1

我正在研究Windows服務的c#程序。如何映射Windows服務程序的文件

我需要使用一個文件。這裏是我的代碼

const string mail_file_path = @"template\mailbody.html"; 

但根據我的日誌,有這樣的錯誤:

Error: Could not find a part of the path 'C:\Windows\system32\template\mailbody.html'.

我用app.configuration使用另一個文件

<add key="TimeStampFilePath" value="timestamp.ini" /> 
StreamReader sr = new StreamReader(ConfigurationManager.AppSettings["TimeStampFilePath"]); 

但我無法讀取文件。

當我作爲一個簡單的Windows控制檯項目運行這個項目,它的工作原理。但是在我使用Windows服務模式運行它之後,出現了兩個問題。

+0

該文件在哪裏?請提供完整的路徑。 – Oded

+0

VS2010 \ Projects \ ProjectName \ bin \ Debug \ template \ mailbody.html VS2010 \ Projects \ ProjectName \ bin \ Debug \ timestamp.init – QianLi

+0

@QuianLi:如果您複製服務器exe文件所在的模板文件夾,我的答案應該可行。 – CharithJ

回答

2

你可以嘗試:

// dir is path where your service EXE is running 
string dir = Path.GetDirectoryName(
    Assembly.GetExecutingAssembly().Location);  
// mail_file_path is where you need to search 
string mail_file_path = Path.Combine(dir , @"\template\mailbody.html"); 

就拿我的答案作爲一個集成@ CharithJ的帖子,這是絕對正確的!

+0

對不起,它仍然不起作用。我應該在哪裏放置模板文件夾? – QianLi

+0

@QianLi:在服務EXE的地方運行並在那裏創建_template_ subdir。看看我的編輯帖子。 – Marco

+0

我已將模板文件夾放入運行foder的服務EXE中,並按照您的建議更改mail_file_path的值。但仍然不起作用,現在錯誤變成了錯誤:找不到路徑'C:\ template \ mailbody.html'而不是舊路徑的一部分錯誤:找不到路徑的一部分'C :\ SYSTEM32 \模板\ mailbody.html」。 – QianLi

0

如果您已將template \ mailbody.html放在服務exe所在的同一目錄中。嘗試下面的內容並參閱。您可以找到Windows服務.exe所在的文件夾。

string mail_file_path = System.Reflection.Assembly.GetEntryAssembly().Location + 
         "\template\mailbody.html"; 

或者,這也可以幫助AppDomain.CurrentDomain.BaseDirectory

0

由於@Macro的建議,我找到了解決問題的方法。我使用REGISTER API獲取windows服務映射目錄,然後將工作目錄設置爲與它相同。然後我可以使用相對路徑來獲取我需要的文件。

相關問題