Reputation: 444
I have a basic service that will be used to run a ClickOnce application every x minutes, however when i run Process.Start() i am receiving an exception that the file cannot be found.
Code
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
WriteToFile("Timer ticked");
CheckProcess(GetProcessName());
}
public void CheckProcess(string ProcessName)
{
WriteToFile(ProcessName);
try
{
Process.Start(ProcessName);
WriteToFile("It ran");
}
catch (Exception ex)
{
WriteToFile(ex.ToString());
}
}
public string GetProcessName()
{
string ProcessName = string.Concat("%AppData%\\Microsoft\\Windows\\Start Menu\\Programs\\", PublisherName, "\\", ProductName, ".appref-ms");
return ProcessName;
}
The error i receive is:
%AppData%\Microsoft\Windows\Start Menu\Programs\PubName\ProdName.appref-ms
System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start(String fileName)
If i run the ProcessName retrieved in explorer then the application launches successfully. Value of ProcessName is :
C:\Users\xxx\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\PubName\ProdName.appref-ms
Is there something i am missing in order to start the file?
Upvotes: 0
Views: 485
Reputation: 1479
Windows Services are the programs which will runs even before a user logged into it's Account. This is Windows Service purpose, and by this definition you haven't access to specific User Environment Variables (Like %AppData%) because you aren't in the User Session so your address will be translated to something Odd if you write it into a .txt you will see the result.
Windows Services (By your definitions) will run by LocalSystem, LocalService or NetworkService. Go to TaskManager->Services->Open Services and watch Log On As
Column.
So you must use a general path which be access-able through your service.
Most terrifying solution is to force your Service to wait for a user login and impersonate his token.
I will Prefer to choose a better place.
There is a way to debug and see your Service bugs (In UserSession) in VisualStudio. Change your Program.cs to something like:
static void Main()
{
#if DEBUG
var MainService = new MainService();
MainService.OnDebug();
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MainService()
};
ServiceBase.Run(ServicesToRun);
#endif
}
and Add OnDebug function to your Service:
public void OnDebug()
{
OnStart(null);
}
if you debug your project in this way you will see that your service is working As Expected !!!
Upvotes: 1