Access to the path is Denied When create file by windows service
c#, windows-services
Solution
The service user account probably doesn't have access to write to `C:\Windows\System32` (which is the working directory of a Windows service).
Anyway, you shouldn't write to that folder. It is for the operating system - not your service.
You can use Environment.GetFolderPath to get a suitable path for writing files like log files in a way that will work any computer, not just your own computer. Here is an example.
var companyPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"MyCompany"
);
var productPath = Path.Combine(companyPath, "MyProduct");
var logFilePath = Path.Combine(productPath, "BridgeServiceLog.txt");
You should of course use suitable values for `MyCompany` and `MyProduct`.
Problem
i cannot create file in my windows service and this is error error In onstart method Access to the path 'C:\Windows\system32\BridgeServiceLog.txt' is denied. ``` 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"); } ```