Unable to find particular file - c#

When in my program I try to launch particular exe-file "nvidia-smi.exe" (NVIDIA System Management Interface program), I receive the error "System.ComponentModel.Win32Exception. The system cannot find the file specified"
string directoryPath = "C:\\";
string fileName = "nvidia-smi.exe";
Console.WriteLine(System.IO.File.Exists(directoryPath + fileName)); //true
proc.StartInfo.WorkingDirectory = directoryPath;
proc.StartInfo.FileName = fileName;
proc.Start(); //Error. The system cannot find the file specified
But at the same time I can :
1) Launch the other files from the same directory (exe, bat etc)
2) Successfully to execute the file I needed "nvidia-smi.exe" if relocate it to my project's directory and do not use the property "proc.StartInfo.WorkingDirectory".
-----------------The answer is (Thanks for help!)------------------
you need this :
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.WorkingDirectory = "C:\\";
proc.StartInfo.FileName = "nvidia-smi.exe";
Or this :
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = "C:\\nvidia-smi.exe";

If you set proc.StartInfo.UseShellExecute to true, the behavior of WorkingDirectory will be as you expect it to be. Otherwise, you will have to either specify the absolute path for the FileName, or make sure your executable is in your environment path.
Relevant documentation:
UseShellExecute
WorkingDirectory

Related

Running multiple commands from C# application

I want to run several commands via C# application like
Previously I had a batch file and I ran it using C# but now few of the commands can take inputs. But how to do that ?
I tried
Process cmdprocess = new Process();
ProcessStartInfo startinfo = new ProcessStartInfo();
Environment.SetEnvironmentVariable("filename", FileName);
startinfo.FileName = #"C:\Users\cnandy\Desktop\St\2nd Sep\New_CN\New folder\Encrypt web.config_RSAWebFarm\Decrypt Connection String.bat";
startinfo.WindowStyle = ProcessWindowStyle.Hidden;
startinfo.CreateNoWindow = true;
startinfo.RedirectStandardInput = true;
startinfo.RedirectStandardOutput = true;
startinfo.UseShellExecute = false;
cmdprocess.StartInfo = startinfo;
cmdprocess.Start();
And in the batch file
cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
aspnet_regiis -pi "CustomKeys2" "C:\Users\cnandy\Desktop\Encryption_keys\CustomEncryptionKeys.xml"
aspnet_regiis -pa "CustomKeys2" "NT AUTHORITY\NETWORK SERVICE"
aspnet_regiis -pdf "connectionStrings" %filename%
But effectively they did not run get executed at all. How to achieve the same where for the last command I can accept an input instead of hard coding
"C:\Users\cnandy\Desktop\Test\Websites\AccountDeduplicationWeb"
?
Try this:
Process p = new Process()
{
StartInfo = new ProcessStartInfo("cmd.exe")
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
p.Start();
using (StreamWriter sw = p.StandardInput)
{
sw.WriteLine("First command here");
sw.WriteLine("Second command here");
}
p.StandardInput.WriteLine("exit");
Alternatively, try this more direct way (which also implements the last thing you requested):
string strEntry = ""; // Let the user assign to this string, for example like "C:\Users\cnandy\Desktop\Test\Websites\AccountDeduplicationWeb"
Process p = new Process()
{
StartInfo = new ProcessStartInfo("cmd.exe")
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
p.Start();
p.StandardInput.WriteLine("cd C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319");
p.StandardInput.WriteLine("aspnet_regiis -pi \"CustomKeys2\" \"C:\\Users\\cnandy\\Desktop\\Encryption_keys\\CustomEncryptionKeys.xml\"");
p.StandardInput.WriteLine("aspnet_regiis -pa \"CustomKeys2\" \"NT AUTHORITY\\NETWORK SERVICE\"");
p.StandardInput.WriteLine("aspnet_regiis -pdf \"connectionStrings\" " + strEntry);
p.StandardInput.WriteLine("exit"); //or even p.Close();
If using the second way, it is recommended to let the user enter the path in a textbox, then grab the string from the textbox's Text property, where all the necessary extra back-slashes will be automatically appended.
It should be mentioned that no cmd will show up running your batch file, or the commands.
You can still make a batch file as you used to. Only change it needs is accepting variables.
Something like
CallYourBatch.bat "MyFileName"
Then in you batch file, you can accept a parameter
SET fileName=%~1
aspnet_regiis -pdf "connectionStrings" %fileName%
Similarly the same functionality can be used while forming your command text, if you must do it as part of C# code.
Also might i suggest using a CALL command to call your batch files? More information on the same is at http://ss64.com/nt/call.html
Start the batch file using Process object. You can use Environment variables to pass the values between processes. in this case, from C# to bat file you can pass values using environment variable.
c#
Environment.SetEnvironmentVariable("searchString","*.txt")
in bat file you can access the value as like below
dir %searchString%
To start the bat file from c#
System.Diagnostics.Process.Start("path\commands.bat");
Sample code to start notepad from C# with Batch file and Variables
System.Environment.SetEnvironmentVariable("fileName", "test.txt");
System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/commands.bat");
Console.ReadLine();
Bat file
#echo "staring note pad"
notepad %fileName%

Executing Batch File From Shortcut

I am trying to execute a batch file from a shortcut application on my desktop. The batch file lives on my C:drive which is where the actual application.exe is.
The problem is the CMD is executing the batch from C:\Users\hap\Desctop> and not from the executable path so it obviously cannot find my .exe file that the batch file is looking for.
Here is what I am using to execute the batch file:
System.Diagnostics.Process.Start(System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\batch_file.bat").WaitForExit();
What you have to do is create a ProcessStartInfo structure and set its WorkingDirectory appropriately.
You should do the following:
string workingDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
ProcessStartInfo info = new ProcessStartInfo()
{
FileName = workingDir + "\\batch_file.bat",
WorkingDirectory = workingDir // or wherever else you want it to execute from
};
Process p = new Process() { StartInfo = info };
p.Start();
p.WaitForExit();

Why is auditpol not applying the local policy settings from C#?

I'm setting local auditing policies from a C# .NET program that reads settings from a file then uses Process.Start() with 'cmd' to execute the commands. This way has worked in the past for everything that I've needed it to do (including this exact situation), but recently it's just started to mysteriously fail to set the policies.
Here's the code: (command is of the form "auditpol /set /subcategory:"blah" /success:enable")
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
string result = proc.StandardOutput.ReadToEnd();
string error = proc.StandardError.ReadToEnd();
In debug in VS2013 it's applying the policies just fine and even on the same computer in the full on .exe it's applying just fine, but when it gets transferred to another computer it will not set the policies from the auditpol command. Anyone have any ideas what could be happening?

Launching a batch file

I have the following code:
String Antcbatchpath = #"C:\GUI\antc.bat";
System.Diagnostics.Process runantc = new System.Diagnostics.Process();
runantc.StartInfo.FileName = Antcbatchpath;
runantc.StartInfo.UseShellExecute = false;
runantc.StartInfo.RedirectStandardOutput = true;
runantc.StartInfo.RedirectStandardError = true;
runantc.Start();
Will this load the batch file from C:\GUI\antc.bat?
Or runantc.StartInfo.FileName is only for a root directory? Root directory is where the application is located
EDIT 1:
hi instead of #"C:\GUI\antc.bat" i have a path:
String Antcbatchpath =#"C:\GUI Lab Tools\Build Machine\antc.bat";
which essentially contains white spaces. will it affect the runantc.StartInfo.Filename = Antcbatchpath; ?
UseShellExecute = true should do it.
Alternatively, if you need redirection, use:
runantc.StartInfo.FileName = "CMD.EXE";
runantc.StartInfo.Arguments = "/C " + Antcbatchpath;
You can try to set WorkingDirectory to prevent any ambiguity, but in my experience, it is not necessary.
The problem you're having is because antc.bat is not an executable. It requires UseShellExecute to be true, but that would prevent you from redirecting the output. I guess you will have to choose either one.

Website runs executable program

My website runs a local .exe file (generates some data), when a user clicks a certain link.
I would like to know how to do the following
what command to use to run the .exe?
where should I store the .exe and still maintain security?
I use .net 4 c#
Not sure if this works in MVC, but give it a shot:
// Process class resides in System.Diagnostics namespace
Process myProcess = Process.Start("...");
myProcess.WaitForExit();
// todo : process your data
Here's something that I use in one of my applications:
var p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = HttpContext.Current.Server.MapFfmpegPath();
p.StartInfo.Arguments = "arguments go here :)";
p.Start();
p.WaitForExit();
As for the executable itself, I created a directory in my project and put the exe in that directory. The MapFfmpegPath method looks something like this.
public static string MapFfmpegPath(this HttpServerUtility server)
{
return "\"" + server.MapPath("/CoolPathHere/ffmpeg.exe") + "\"";
}

Categories

Resources