Program crashes when starting process.Start() at windows start up - c#

I have 2 exe, A.exe and B.exe. A.exe is added to the registry's run key so that it starts with windows start up.
Inside of A's main, there is this code:
Process pr = new Process();
pr.StartInfo.FileName = "B.exe";
pr.StartInfo.Arguments = SomeArgs;
pr.Start();
Both A and B is in the same directory. If I launch A manually by double clicking it, it works fine, B starts up fine. But, when I tried to restart windows to check if it works fine at windows start up, every time A.exe crashed and hence B.exe was never launched. I thought it was some other problem in A, maybe system was slow to load some dependencies but no, when I removed the above part of code, everything works fine on windows start up, A dont crash but B is not launched. So what could be the problem or how to solve this?
Edit: used a try catch, and this came up, I have no idea why this came up though:
System.ComponentModel.Win32Exception: The system cannot find the file
specified at
System.Diagonstics.Process.StartWithShellExecuteEx(ProcessSt‌​artInfo
startInfo) at System.Diagonostics.Process.Start() at
System.Diagonostics.Process.Start(ProcessStartInfo startInfo) at
System.Diagnostics.Process.Start(String fileName, String arguments) at
....
I even tried with full file path still same error. But, manually launching it causes no error and works perfectly fine. Its just that this windows start up is messing it up.

try that one
Process pr = new Process();
pr.StartInfo.FileName = Application.StartupPath+"/B.exe";
pr.StartInfo.Arguments = SomeArgs;
pr.Start();

I believe you may be running into a Security error. Process requires certain permissions to work. See the Security section notes here:
Process Class
Figure out a way to log the issue and see if this is the problem you are running into.

Try to specify WorkingDirectory:
Process pr = new Process();
pr.StartInfo.WorkingDirectory = #"C:\path\to";
pr.StartInfo.FileName = "B.exe";
pr.StartInfo.Arguments = SomeArgs;
pr.Start();

Related

C# Console Application fails reading files on restart

Its hard to place everything in the title, but I hope I can explain this as good as I can. Basicly I made a C# Console Application that reads a certain file every now and then. The Application runs on a Virtual Machine from Google Instances. Now I have created another Console Application that is capable of managing the other application, like closing them or restarting the executables.
The Issue:
When I start the Console Application by hand (manual), it works fine and reads the files like it should. I could close and open this as much as I like and it still works. The problem is when my second Console Application tries to restart the first Console Application. The restart works fine and most functions like certain ftp connections work, but it stops reading files and gives a null back as result. There happen to be no debug errors nor does it display an error on the console.
What I want is that the second application could restart my first application without making it run where some functions appear to be blocked.
The Code I use:
string loc = File.ReadAllText(Directory.GetCurrentDirectory() + "\\"+ "location.txt");
Process p = new Process();
p.StartInfo.FileName = loc;
p.StartInfo.UseShellExecute = true;
p.Start();
I tried running it as p.StartInfo.Verb = "runas"; but this has no positive result either. Could this be an issue with the Google Virtual Machine, possible firewall settings or code related issues.
Extra
This code does work on my own laptop and so does it work after restarting.

C# process cannot run on IIS

I have a web application that has to open a process and wait for exit.
This process is a .sh script that uses Cygwin.
I'm using the following code:
var process = new Process();
var string processFileLocation = #"C:\script.sh";
var string workingDirectoryLocation = #"C:\script";
var processInformation = new ProcessStartInfo(processFileLocation)
{
WorkingDirectory = workingDirectoryLocation,
UseShellExecute = true
};
process.StartInfo = processInformation;
process.Start();
process.WaitForExit();
If I run the application using IISExpress, everything works fine, the script is being callse.
When I add it to IIS, the process simply gets blocked, I never receive any answer from the request that should call the process.
I added "Full control" permission to that folder for the Application Pool that the website uses, but still no diference.
Any idea why it is behaving like this?
Whenever something stops running when put in IIS, there's a high likelihood that it's due to insufficient permissions. Start by running your pool with an administrator account. If it solves the issue, then you can work your way from there to find what permission you were missing.

Process.Start(); as another user works but explorer.exe iexplore.exe throws exception

I'm having problems with a program and its buttons (I know, I'm awesome lol) the buttons can be "programmed" to run programs. They also can be set to run as admin (different credentials).
If I set up simply notepad or cmd or explorer it runs like charm. But if I start iexplore it has got no admin rights.
I had problems before with running explorer.exe the solution was that I had to run it by typing the full path C:\windows\explorer.exe to be able to run it but that I solved it by setting up the VB2015 compiler (?) to Platform target: x64.
My other problem is that if I try to run dsa.msc or generally anything ends with msc it throws the following exception, even if I set up the full path to the syswow64 (or the system32) folder like c:\windows\syswow64\dsa.msc
"The specified executable is not a valid application for this OS platform."
Running the C:\Windows\System32\mmc.exe "services.msc" (or syswow64, with or without the /computer= switch) throws
"The requested operation requires elevation." which I have since I'm able to run services.msc (and all other msc-s from command line with the same user rights)
Thank you.
A beginner.
Basically you don't need to run the host app as administrator! There is a variable (inside your Process instance) called StartInfo (which is an instance of the ProcessStartInfo Class), where Verbs could be used as followed:
Process p = new Process()
{
StartInfo = new ProcessStartInfo("E:\\Users\\Temp\\app.exe")
{
Verb = "runas"
}
};
p.Start();
This will prompt the user to run the app.exe as administrator.
Edit
Running a Process as a defined user:
Process p = new Process()
{
StartInfo = new ProcessStartInfo("E:\\Users\\Temp\\app.exe")
{
Verb = "runas",
Arguments = "/user:Vira"
}
};
For more information about those RUNAS Arguments, click me! :)

Process.Start in C# The system cannot find the file specified error

This is a silly and tricky issue that I am facing.
The below code works well (it launches Calculator):
ProcessStartInfo psStartInfo = new ProcessStartInfo();
psStartInfo.FileName = #"c:\windows\system32\calc.exe";
Process ps = Process.Start(psStartInfo);
However the below one for SoundRecorder does not work. It gives me "The system cannot find the file specified" error.
ProcessStartInfo psStartInfo = new ProcessStartInfo();
psStartInfo.FileName = #"c:\windows\system32\soundrecorder.exe";
Process ps = Process.Start(psStartInfo);
I am able to launch Sound Recorder by using Start -> Run -> "c:\windows\system32\soundrecorder.exe" command.
Any idea whats going wrong?
I am using C# in Visual Studio 2015 and using Windows 7 OS.
UPDATE 1: I tried a File.Exists check and it shows me MessageBox from the below code:
if (File.Exists(#"c:\windows\system32\soundrecorder.exe"))
{
ProcessStartInfo psStartInfo = new ProcessStartInfo();
psStartInfo.FileName = #"c:\windows\system32\soundrecorder.exe";
Process ps = Process.Start(psStartInfo);
}
else
{
MessageBox.Show("File not found");
}
Most likely your app is 32-bit, and in 64-bit Windows references to C:\Windows\System32 get transparently redirected to C:\Windows\SysWOW64 for 32-bit apps. calc.exe happens to exist in both places, while soundrecorder.exe exists in the true System32 only.
When you launch from Start / Run the parent process is the 64-bit explorer.exe so no redirection is done, and the 64-bit C:\Windows\System32\soundrecorder.exe is found and started.
From File System Redirector:
In most cases, whenever a 32-bit application attempts to access %windir%\System32, the access is redirected to %windir%\SysWOW64.
[ EDIT ] From the same page:
32-bit applications can access the native system directory by substituting %windir%\Sysnative for %windir%\System32.
So the following would work to start soundrecorder.exe from the (real) C:\Windows\System32.
psStartInfo.FileName = #"C:\Windows\Sysnative\soundrecorder.exe";
Old thread but providing one more possible case
In my case i was using arguments inside Process.Start
System.Diagnostics.Process.Start("C:\\MyAppFolder\\MyApp.exe -silent");
I changed it to
ProcessStartInfo info = new ProcessStartInfo("C:\\MyAppFolder\\MyApp.exe");
info.Arguments = "-silent";
Process.Start(info)
Then it worked.
One more case, similar to Ranadheer Reddy's answer, but different enough to trip me up for awhile.
I was making a simple mistake. I had this:
ProcessStartInfo info = new ProcessStartInfo("C:\\MyAppFolder\\MyApp.exe ");
info.Arguments = "-silent";
Process.Start(info);
See that space after the end of the path to the app? Yeah. It doesn't like that. It will not find your file if you include that.
The solution was to remove the extraneous space. Then it worked.
This is an easy enough mistake to make if you're converting an app from starting processes by launching "cmd.exe /c MyApp.exe -silent" to running "MyApp.exe" directly instead, which is what I was doing. I hope recording my misfortune here will help future developers.

How to start an exe from a .NET Windows Service for updating the service

I have a windows service that I would like to be automatically and silently updated. I started using wyBuild to implement this, but have had some issues with it, and decided to try to build my own. I've written a standalone exe that can be called to do the update procedure: checks for a new zip file with the update, downloads it, unzips, stop the windows service, copy files from the zip, then restart the service. This exe works fine when I run it from the commandline and wasn't really difficult to write.
However, now I would like the service (the same one being updated) to shell out to the updater exe to update itself. I first tried Process.Start:
var proc = Process.Start(pathToUpdaterExe);
proc.WaitForExit(60000);
This called the updater, but when the updater stops the service, the process is killed and the update stops. I did some searching and it sounds like the solution is to use a separate AppDomain. This is what I have now:
Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
Evidence objEvidence = new System.Security.Policy.Evidence(baseEvidence);
AppDomainSetup setup = new AppDomainSetup();
var updateDomain = AppDomain.CreateDomain("updateDomain", objEvidence, setup);
updateDomain.ExecuteAssembly(updater);
AppDomain.Unload(updateDomain);
However, now I get the error System.IO.IOException: "The process cannot access the file 'C:\Program Files (x86)\Company\Service\Service.dll' because it is being used by another process" when attempting to copy over the new Service.dll
Again, I've stopped the service at this point. I've confirmed this with logging. I can't imagine what would have Service.dll still locked, so I added code to check to see what is locking it:
public static IEnumerable<Process> GetProcessesLocking(string filePath)
{
var result = new List<Process>();
result.Clear();
var processes = Process.GetProcesses();
foreach (Process proc in processes)
{
try
{
if (proc.HasExited) continue;
foreach (ProcessModule module in proc.Modules)
{
if ((module.FileName.ToLower().CompareTo(filePath.ToLower()) == 0))
{
result.Add(proc);
break;
}
}
}
catch (Exception ex)
{
Log(ex.ToString());
Log("There was an error checking " + proc.ProcessName );
}
}
return result;
}
However this code indicates that nothing has a lock on the dll (result is empty and nothing is logged indicating an error).
I suspect I'm running afoul of some UAC issue that is the real cause of the IOException. The windows service runs as LocalSystem. All that to ask: How should I be running the update exe from the windows service such that it has rights to copy files in c:\Program Files?
Update
As the comments and answer suggest, Process.Start can work, but there is some nuance. You have to start cmd.exe and use it to start the updater. I also found I could not use a full path for the updater exe and that I needed to set UseShellExecute=false. This is my final working code that launches the updater from the .NET service:
var cmd = "/c start updater.exe";
var startInfo = new ProcessStartInfo("cmd.exe");
startInfo.Arguments = cmd;
startInfo.WorkingDirectory = AssemblyDirectory;
startInfo.UseShellExecute = false;
var proc = Process.Start(startInfo);
I did this exact thing - using a simpler (some might say kludgy) approach. The service:
Produces a batch command,
Downloads the new executables to a staging location,
Starts a process: cmd.exe which, in turn, runs the batch script w/o waiting for it to complete, and then
Immediately terminates itself.
The batch command:
Pings 127.0.0.1 five times,
Copies the executables to the final location and,
Restarts the service.
Works like clockwork. The ping is a reliable 5 second delay - lets the service shutdown before copying the files.
Edit:
Just for completeness - I realized that by batch cmd is pinging 127.0.0.1 not 128.0.0.1 and so I edited this answer to reflect that. I suppose either works - but 128.0.0.1 pings timeout, where 127.0.0.1 resolves to "me". Since I'm only using it as a poor-man's delay, it serves the purpose either way.

Categories