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();
Related
Executing by C# a complicated batch file, that setting session variables example
SET TEST = rainbow
getting the famous
A duplicate file name exists, or the file cannot be found.
I used
string args = string.Format("/k \"cd /d {0} && {1}\"", s.Path, s.Filename + " " + userChoice);
RunBatch("cmd.exe", args, s.Path);
.
.
ProcessStartInfo startInfo = new ProcessStartInfo()
{
UseShellExecute = false,
WorkingDirectory = workingDir,
FileName = cmd,
Arguments = cmdArgs
};
Process.Start(startInfo);
when trying it on simple batch file working. With the complex one getting the error mention above.
--
I tried also to write by C#, a new batch file that has on the first line the
setlocal enableextensions disabledelayedexpansion
, then calling the needed one, and execute this batch by C#, the error again is the same...
any tip?
I am developing one console application that will convert all spss (.sav) files to .csv files. For this I created a SPSS job (spssJob1.spj) manually (using one .sps file) and I am iterating through all the input files (all .sav files) and trying to run that job by updating the input and output path in the .sps file (text.sps). But I don't know how to call that job execution command from my app.
Currently, the command is:
stats C:\Users\10522\Desktop\spssJob1.spj -production
and this should be executed from
C:\Program Files\IBM\SPSS\Statistics\22
because this stats command will be available only in this directory.
So in my app I need to call this process from this path; I am able to call one .exe file by using my app but I don't know how to call one command form a specific directory.
This is my code:
// getting all spss files from the from the input path
FileInfo[] Files = new DirectoryInfo("D:\Input").GetFiles("*.sav");
// looping each files and calling the job
foreach (FileInfo file in Files)
{
if (file.Name != "")
{
// updating the text.sps file for each job
System.IO.File.WriteAllText("D:\Input\text.sps", string.Empty);
System.IO.File.WriteAllText("D:\Input\text.sps", (Content for the file));
// calling the process
var p = new Process();
// this code will work fine simply calling one exe
p.StartInfo = new ProcessStartInfo((#"D:\Input\temp.exe"), "-n")
// instead of this I need to call something like this
// stats C:\Users\10522\Desktop\spssJob1.spj -production from this
// path C:\Program Files\IBM\SPSS\Statistics\22
{
UseShellExecute = false
};
p.Start();
p.WaitForExit();
}
}
ProcessStartInfo pi = new ProcessStartInfo("stats");
pi.Arguments = #"C:\Users\10522\Desktop\spssJob1.spj -production";
pi.WorkingDirectory = #"C:\Program Files\IBM\SPSS\Statistics\22";
pi.UseShellExecute = false;
Process.Start(pi);
you can do this by altering ProcessStartInfo's properties.
Not sure what stats is, if its an exe then you can specify the full exe path and just omit working directory.
var p = new Process();
p.StartInfo = new ProcessStartInfo("stats")
{
//UseShellExecute = false,
Arguments= #"C:\Users\10522\Desktop\spssJob1.spj -production",
WorkingDirectory = #"C:\Program Files\IBM\SPSS\Statistics\22",
};
p.Start();
p.WaitForExit();
My compiled AutoIt script runs fine by itself but when called from C# it will run but does not finish executing. My compiled C# code:
Process myExe = new Process();
Environment.CurrentDirectory = Path.GetDirectoryName(exeDir); //exeDir is full path of the AutoIt executable directory
ProcessStartInfo StartInfo = new ProcessStartInfo("");
StartInfo.FileName = exeFile; //exeFile is full path of the executable itself
StartInfo.Verb = "runas";
myExe = Process.Start(StartInfo);
It halts on EnvUpdate() in the AutoIt code and eventually again on some other function. None of this happens if I run the executable manually.
I started a batch file from C# that runs this executable. And combinations of CreateNoWindow and UseShellExecute. Also with no success:
1) Run the C# compiled executable as Admin.
2) Use combinations of StartInfo.CreateNoWindow and StartInfo.UseShellExecute.
3) Run AutoIt executable from a batch file.
4) Run AutoIt executable from a Perl file, through a batch file.
5) Run AutoIt executable from a Windows scheduled task.
6) Run AutoIt executable without ProcessStartInfo, with either:
myExe = Process.Start("cmd.exe", "/c start /wait " + exeFile);
or
myExe = Process.Start(exeFile);
Here an example C# class for an external call to a compiled AutoIt script (EXE file) using .WaitForExit(), which should be your problem:
using System.Configuration;
using System.Diagnostics;
namespace RegressionTesting.Common.ThirdParty
{
public class ClickAtBrowserPosition
{
public static void CallClickAtBrowserPosition(string currentBrowserWindowTitle, int xPosition, int yPosition)
{
var pathClickAtBrowserPosition = ConfigurationManager.AppSettings["pathClickAtBrowserPosition"];
var clickAtBrowserPositionExe = ConfigurationManager.AppSettings["clickAtBrowserPositionExe"];
var process = new Process();
var startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden, // don't show the cmd.exe which calls the program
FileName = "cmd.exe",
Arguments = #" /C cd " +
$#"""{pathClickAtBrowserPosition}"" && {clickAtBrowserPositionExe} ""{currentBrowserWindowTitle}"" {xPosition} {yPosition}"
};
process.StartInfo = startInfo;
process.Start();
process.WaitForExit(); // wait to finish the execution
}
}
}
The compiled AutoIt script is used for clicking a relative position of a window (in this case a browser).
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%
I have an exe that I would like to use by executing it with command line parameters.
var query = Path.Combine(path, calculator.ExeName + ".exe");
var p = new Process();
p.StartInfo.FileName = query;
//the command line parameter that causes the exe to start in an invisible mode
p.StartInfo.Arguments = "episrc"
p.Start();
This code works and it starts the exe but there's one problem : the exe is supposed to be writing on a file in its directory but that doesn't happen. The process exits successfully (Exitcode0). What could be the cause of this problem?
I have a Delphi code that executes successfully the exe and the exe writes to the file but it's using the ExecProcess from win32 API thus the exe is valid and working.
Also if I try to execute it from the command prompt like so : kowwinnt.exe episrc it writes to the file successfully.
You should set the Working Directory.
Your code would look like this:
var query = Path.Combine(path, calculator.ExeName + ".exe");
var p = new Process();
p.StartInfo.FileName = query;
p.StartInfo.WorkingDirectory = path;
//the command line parameter that causes the exe to start in an invisible mode
p.StartInfo.Arguments = "episrc"
p.Start();