Hoping this question will get answered. Basically I am attempting to open an executable file from within an application I have created which runs on windows ce5 on a unitech barcode scanner using the .net compact framework 3.5. I have included a snippet of code where I attempt this.
Each time I debug the app via VS2008 I am getting a Win32Exception but with no further details (with or without the try catch statement). It does not tell me what the exception is nor does it provide an error code.
Here is the code I am using to try to start the process. Can you see anything wrong with it that may be causing an error? I have double and triple checked the filename and also the directory where it is stored so it is not that.
private void CustomButtonEvent(object sender, EventArgs e)
{
string buttonName = ((Control)sender).Name;
ProcessStartInfo processStartInfo = new ProcessStartInfo();
buttonName = buttonName.Remove(0, 3);
buttonName = buttonName.Replace(' ', '_');
switch (buttonName)
{//todo need to open the different exe's here
case "End_Of_Line":
{
MessageBox.Show(#"No app behind this button yet.");
break;
}
case "Asset_Tracking":
{
processStartInfo.FileName = "AssetTrackingScanner.exe";
processStartInfo.WorkingDirectory = #"\Flash Storage\CompoundingManagementScannerSuite\Applications\AssetTrackingScanner\AssetTrackingScanner\bin\Debug";
try
{
Process.Start(processStartInfo);
}
catch (Exception f)
{
MessageBox.Show(f.ToString());
}
break;
}
case "Stock Take":
{
MessageBox.Show(#"No app behind this button yet.");
break;
}
case "Despatch":
{
MessageBox.Show(#"No app behind this button yet.");
break;
}
}
}
I see two problems. First, CE requires fully qualified paths, so the processStartInfo.FileName should be something like this
processStartInfo.FileName =
#"\Flash Storage\CompoundingManagementScannerSuite\Applications\AssetTrackingScanner\AssetTrackingScanner\AssetTrackingScanner.exe";
Second, CE has no concept of a WorkingDirectory, so remove the call to set it.
I'm also a little concerned about the \bin\debug\ part of your path. Studio doesn't deploy to a bin\debug\ folder on the device. It build to one on the PC, but on the target device the only way it would be there is if you manually set it. This leads me to think you need to check your on-device applicatin path.
Related
I have a WPF-Application that I would like to start automatically if I start my Computer.
I have a window where a user can configure some settings for the application, one of the possible configuration options is a checkbox, that allows the user to dis- or enable the application to automatically start on the System-Startup.
This is how I set or delete the value in the Registry, depending on the users choice in the Checkbox:
try
{
var currentAssembly = Assembly.GetExecutingAssembly();
var rkApp = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (settingsViewModel.AutostartEnabled)
{
rkApp.SetValue(currentAssembly.GetName().Name, currentAssembly.Location);
}
else
{
rkApp.DeleteValue(currentAssembly.GetName().Name, false);
}
}
catch (Exception exception)
{
}
My Problem is, that even though the Application gets registered and can also be seen in the Autostart-Section within the Task-Manager, that I get the following error every time I restart my computer to check if the Appliction is started:
"You are attempting to open a file of type Application extension (.dll)"
So what am I doing wrong? Is there any way to avoid this error or to fix it? I already tried adding an application manifest file to my project to always start my Application as an Administrator. But that didn't seem to work either.
I'd appreciate any help.
Try to use System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName instead of currentAssembly.Location.
This should give you the path of the running executable. Assembly.GetEntryAssembly does not.
I have written an application that installs Windows Roles and Features using the Powershell API. It works just fine in Windows 2008 R2, but nothing happens in Windows 2012; the program just moves on as if everything happened just fine, but nothing is installed.
I've tried making the program .NET v4.5 (it was .NET v2.0), but that didn't help. I've been all over Google about this and I can't find a solution that works. In fact, most say to use the sort of implementation that works in Windows 2008 R2. Here is my code:
public bool runPowerShell(string command, string args)
{
mLogger myLogger = mLogger.instance; //How I log stuff in my application.
bool done = false; //default Return value.
const string path = #"C:\\XMPLogs\\Roles and Features"; //Where Powershell output will go.
//Make sure Powershell log directory is there.
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
//Start a new Powershell instance.
PowerShell powershell = PowerShell.Create();
System.Collections.ObjectModel.Collection<PSObject> output = new System.Collections.ObjectModel.Collection<PSObject>();
StringBuilder strBuilder = new StringBuilder(); //Used to examine results (for testing)
powershell.AddScript(#"Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted");
powershell.AddScript(#"Import-Module ServerManager");
//powershell.Invoke();
powershell.AddScript(command + " " + args);
try
{
output = powershell.Invoke();
// Construct a StringBuilder to examine the output of Invoke()
foreach (PSObject obj in output)
strBuilder.AppendLine(obj.ToString());
// Show the StringBuilder to see results (always empty!)
MessageBox.Show(strBuilder.ToString());
done = true;
}
catch (Exception ex)
{
string test = ex.ToString();
MessageBox.Show(test);
myLogger.output("ERRO", "PowerShell command " + command
+ "failed to run with arguments \"" + args + "\". Message: " + ex.ToString());
done = false;
}
powershell.Dispose();
return done;
}
I would call the method like this:
runPowerShell("add-windowsfeature", "-name FS-FileServer -logpath \"c:\\XMPLogs\\Roles and Features\\File Services.log\"");
The "output" object never has any data in it nor does the log file. So, I have no idea what is going on. I do know if I take the two parameters in the method call and enter them into a Powershell prompt manually, the install runs flawlessly.
Can anyone see what I'm doing wrong with this implementation on Windows Server 2012?
Thank you.
It's hard to know what is the real problem here, without more information. Perhaps you're not running your application as an administrator and therefore aren't allowed to add windows features?
However, PowerShell differs between terminating errors (which would block the execution and throw an exception, which should make your code enter the catch statement) and non-terminating errors (which are just written to the error stream and will not enter your catch statement).
You can read more about this if you run Get-Help Write-Error, Get-Help about_Throw and Get-Help about_Try_Catch_Finally.
I'm guessing your powershell command results in a non-terminating error. To find out whether a non terminating error has occured or not, you could check the powershell.HadErrors property and to get the error messages you can read the powershell.Streams.Error property.
This should probably help you in finding out what errors are occuring and hopefully help you solve your problem.
I'm running a tool that samples the HW PCI for a specific value (I didn't write it).
When I run it from the command prompt, it returns one exit code (the correct one) but when I run it from another application using Process.Start, it returns another exit code.
Is there a difference between running an application directly or via Process.Start?
Do you know of a simple workaround for this issue?
As stated in Hassan's answer (which solved my similar issue), the exit code returned from Process.Start() is affected by the location of the executable, in particular which directory it is located in. Here's the code I used:
string yourExe = "C\\Program Files\\Your Directory\\YourExe.exe";
string currentDir = Directory.GetCurrentDirectory();
string yourExeDir = "C\\Program Files\\Your Directory";
try
{
Directory.SetCurrentDirectory(yourExeDir);
}
catch (DirectoryNotFoundExeption dnfe)
{
MessageBox.Show("The specified directory does not exist. " + dnfe.Message);
}
if (!File.Exists(yourExe))
{
MessageBox.Show("Can't find yourExe");
}
else
{
Process.Start(yourExe);
}
try
{
//Set the current directory.
Directory.SetCurrentDirectory(currentDir);
}
catch (DirectoryNotFoundException dnfe)
{
MessageBox.Show("The specified directory does not exist. " + dnfe.Message);
}
This switches the current working directory to the directory where the .exe is located, runs it, and then switches back to whatever your previous working directory was.
If you want the same result from Process.Start(), you have to execute your application on
the same working directory as your command line.
When I execute an exe file (PVFProject15.exe), it reads the data from an input file (inputFile.txt) and print the results in another file (outputFile.txt). The exe file works well when I double click it; It opens the console window which stays opened until the output file is created. However, when I run (PVFProject15.exe) from c#, the console window opens and closes very quickly and the output file is never created.
I would really appreciate your help since I have been working to fix this for a whole day and never found the answer. Here is my code below.
private void button1_Click(object sender, EventArgs e)
{
Process runFortran = new Process();
try
{
runFortran.StartInfo.FileName = "C:\\temp\\trial\\PVFProject15.exe";
runFortran.Start();
runFortran.WaitForExit();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Thank you in advance.
Safaa
Probably PVFProject15.exe needs current directory to be set to C:\temp\trial
If PVFProject15.exe writes to file using relative path, look for outputFile.txt in directory from which you start your main program-bootstrapper.
I also meet with same problem, when I try start some .exe and .hta from my C# based software.
I start to looking for solution and answer of Mike Mozhaev get to me right direction.
In your code you need to use:
StartInfo.WorkingDirectory = Convert.ToString( System.IO.Directory.GetParent(appPath));
So code have to be like this:
if (File.Exists(appPath))
{
Process runProcess = new Process();
runProcess.StartInfo.WorkingDirectory = Convert.ToString( System.IO.Directory.GetParent(appPath));
runProcess.StartInfo.UseShellExecute= true;
runProcess.StartInfo.FileName = appPath;
runProcess.Start();
}
I have windows forms application wich runs another console application
here is the part of code
prog = new Process();
prog.StartInfo.FileName = exefile;
The console application should create file but when running that application from C# it doesn't creates any file
when im running console application with double click it works fine
here is the part of code from "exefile" (its on c++)
freopen("file.in","r",stdin);
freopen("file.out","w",stdout);
printf("somedata\n");
"file.in" surely exists
The most likely thing is that you need to set the working path:
prog.StartInfo.WorkingDirectory = ...
i.e. I'm thinking it can't find file.in in the current app folder.
You need to add this line whenever you want to start the process:
prog.Start();
Here is the link to the MSDN page for Process.Start. There are several overloads that you may want to consider.
I would suggest,
handle exceptions to see what's going wrong
like mentioned before make sure you
call the start() method
Here's a snippet of code from msdn, that you might want to refer
Process myProcess = new Process();
try
{
// Get the path that stores user documents.
string myDocumentsPath =
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
myProcess.StartInfo.FileName = myDocumentsPath + "\\MyFile.doc";
myProcess.StartInfo.Verb = "Print";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
}
catch (Win32Exception e)
{
if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND)
{
Console.WriteLine(e.Message + ". Check the path.");
}
else if (e.NativeErrorCode == ERROR_ACCESS_DENIED)
{
// Note that if your word processor might generate exceptions
// such as this, which are handled first.
Console.WriteLine(e.Message +
". You do not have permission to print this file.");
}
}