[英]Access to the path is Denied When create file by windows service
我無法在Windows服務中創建文件,這是錯誤的
錯誤在onstart方法中,拒絕訪問路徑'C:\\ Windows \\ system32 \\ BridgeServiceLog.txt'。
protected override void OnStart(string[] args)
{
try
{
Logger.InitLogFile("BridgeServiceLog.txt");
Trace.WriteLine(Logger.logSwitch.TraceInfo, "Trace Started");
Trace.WriteLineIf(Logger.logSwitch.TraceInfo, "OnStart Started");
_bridgeServiceEventLog.WriteEntry("new OnStart");
if (Vytru.Platform.Bridge.Configuration.LicenseValidetor.ValidCountAndTypeDevices())
{
SharedData.InitializeBridge();
// WsInitializeBridge();
}
else
{
this.Stop();
_bridgeServiceEventLog.WriteEntry("LicenseValidetor Error");
}
_bridgeServiceEventLog.WriteEntry("end Start");
}
catch (Exception e)
{
Trace.WriteLineIf(Logger.logSwitch.TraceError, e.Message);
_bridgeServiceEventLog.WriteEntry("error In onstart method " + e.Message);
}
Trace.WriteLineIf(Logger.logSwitch.TraceInfo, "OnStart Ended");
}
服務用戶帳戶可能無權寫入C:\\Windows\\System32
(這是Windows服務的工作目錄)。
無論如何,您不應該寫入該文件夾。 它用於操作系統,而不是您的服務。
您可以使用Environment.GetFolderPath來獲取合適的路徑,以一種適用於任何計算機(而不僅僅是您自己的計算機)的方式來寫入日志文件之類的文件。 這是一個例子。
var companyPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"MyCompany"
);
var productPath = Path.Combine(companyPath, "MyProduct");
var logFilePath = Path.Combine(productPath, "BridgeServiceLog.txt");
您當然應該為MyCompany
和MyProduct
使用合適的值。
運行Windows服務時,默認工作文件夾為<System drive>:\\Windows\\System32\\
。
幸運的是,並非所有人都可以訪問該文件夾。
有兩種解決方法: 將文件寫入您擁有權限的另一個文件夾,或使用管理員權限運行服務。
我建議第一個選擇。
最簡單的解決方案是轉到要保存文件的文件夾,右鍵單擊,屬性,安全性,添加新用戶IIS_Users並授予寫權限。
在ProjectInstaller上使用LocalSystem帳戶
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.