This is my codes
ProcessStartInfo ps = new ProcessStartInfo();
ps.FileName = #"C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python37\\python.exe";
ps.WindowStyle = ProcessWindowStyle.Normal;
ps.Arguments = string.Format("C:\\Users\\Admin\\Downloads\\order.py-master\\order.py-master\\order.py -a 999 -b ",this.textbox.Text);
Process.Start(ps);
There is a function that I am using in my project that is called "RunBat" which runs bat files, but can really work on any file extension such as .py as well.
RunFile.RunBat("Directory/To/Script.py", true);
The way this was possible was by using Process.Start() and setting the path into the base directory, so all you would need to do is input the rest of the directory that leads to the file.
public static int RunBat(string currentFile, bool waitexit)
{
try
{
string path = AppDomain.CurrentDomain.BaseDirectory;
Process process = new Process();
process.StartInfo.FileName = path + currentFile;
process.Start();
if (waitexit == true)
{
process.WaitForExit();
}
return 0;
}
catch
{
return 1;
}
}
The bool waitexit is an optional setting to keep the prompt open while it does it's commands. You can turn this off by using false.
If this fails to work, and you are trying to run a file that is NOT added as a resource in the code, then you would want to change the string path = AppDomain.CurrentDomain.BaseDirectory; to C:\\.
What this will do is instead of starting from the base directory of the application, it will start from the C:\ drive, and then you would continue the rest of the directory in currentFile.
I followed this_link and I was able to run a dummy python file from my c# code like this...
public JsonResult FetchscrapyDataUrl(String website)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:\ProgramData\Anaconda3\python.exe";
start.Arguments = #"C:\Users\PycharmProjects\scraping_web\scrape_info\main.py";
//this is path to .py file from scrapy project
start.CreateNoWindow = false; // We don't need new window
start.UseShellExecute = false; // Do not use OS shell
//start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
Console.WriteLine("Python Starting");
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
Console.Write(result);
}
}
}
Now I know that I can run scrapy spider from a single file main.py like this...
from scrapy import cmdline
cmdline.execute("scrapy crawl text".split())
When I run main.py file from cmd in windows it works fine but it does not work when I run it from C# code .Net framework. The error is ...
"Scrapy 1.4.0 - no active project\r\n\r\nUnknown command: crawl\r\n\r\nUse \"scrapy\" to see available commands\r\n"
Any Idea how to run this...Or am i missing some path setting in windows ??
Or should I run my spider from C# in some other way??
You need to set the WorkingDirectory property
start.WorkingDirectory = #"C:\Users\PycharmProjects\scraping_web\scrape_info\"
Or you need to cd to that directory to make it work
I added to my application folder with exe file that i want to run from my application but i think I did not run the exe file properly.
For example my folder name is folder and the exe file is run.exe so i try #"\folder\run.exe" but The system cannot find the file specified.
what is the correct way to do it ?
public void run(string filePath, int deviceNumber)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo(#"\folder\run.exe");
processStartInfo.Arguments = string.Format("{0} {2}{1}{2}", (deviceNumber).ToString(), filePath, "\"");
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;
processStartInfo.ErrorDialog = false;
using (Process process = Process.Start(processStartInfo))
{
process.WaitForExit();
}
}
ISSUE SOLVED:
the way to do it is ProcessStartInfo processStartInfo = new ProcessStartInfo(System.Windows.Forms.Application.StartupPath + myEXEpath);
If you run it using Process Class remove the leading backslash
#"folder\run.exe"
The directory "folder" must be in the same directory with your executable.
When you start your app from VS you could start processes programatically like this:
Process.Start(#"C:\somepath\run.exe");
You can set the process path relative to your app path.
Like that:
Process.Start(AppDomain.CurrentDomain.BaseDirectory+"run.exe");
You can run this from program.cs and run it at same time of you application start or start it on an other event like form load, or a button click.
I'm trying to fix an issue with the owner on a folder. I am using SetACL. I can use cmd and make the arguments work, but when I try adding it to a program...it doesn't work. I've set a break point to ensure the argument is passed right and it was. Any help is welcome.
Process p = new Process();
if (Wow.Is64BitOperatingSystem == true)
{
p.StartInfo.FileName = "SetACLx64.exe";
}
else
{
p.StartInfo.FileName = "SetACLx86.exe";
}
string command = #" -on """ + path +
#""" -ot file -actn setprot -op ""dacl:np;sacl:nc"" -actn setowner -ownr ""n:" + account + #";"" -rec cont_obj";
p.StartInfo.Arguments = command;
p.Start();
I have got this to work in the same program for a registry issue without trouble. Just can't get this example to work. Folder I'm try to set is the %temp% folder.
If it is running as admin as Sanjeevakumar asked then
Try removing the first space in your command variable. The Arguments parameter does not require that you provide an initial space for the arguments. May be that causes the problem.
Also try tapping into the error data of your process by adding the following lines before calling the Start() method.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.ErrorDataReceived += new DataReceivedEventHandler(ErrorDataHandler);
And then define the event handler.
private static void ErrorDataHandler(object sendingProcess, DataReceivedEventArgs e)
{
//using the DataReceivedEventArgs see if there is an error.
//If it comes there there is most likely an error.
}
So your code does not work when path is "%temp%"? In that case the solution is simple: variable expansion is not done by SetACL but the command shell before SetACL is even started. If you start SetACL directly without invoking cmd.exe then variable expansion never takes place.
You have two options:
Expand "%temp%" in C# code with Environment.GetEnvironmentVariable.
Call SetACL via cmd like this: cmd /c SetACL -on %temp% -ot file ...
I´m trying to run an old .NET application from an ASP.NET website. After reading the web and Stackoverflow (for similar problem) I come to the following code.
The Problem is that I get always an error code (I am using administrator account
just to testing purposes). If I run the exe manually it works ok.
private void Execute(string sPath)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.UserName = "administrador";
string pass = ".............";
System.Security.SecureString secret = new System.Security.SecureString();
foreach (char c in pass) secret.AppendChar(c);
proc.StartInfo.Password = secret;
proc.StartInfo.WorkingDirectory = ConfigurationManager.AppSettings["WORKINGDIRECTORY"].ToString();
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.FileName = sPath;
proc.Start();
proc.WaitForExit();
string result = proc.StandardOutput.ReadToEnd();
Response.Write(result + " - " + proc.ExitCode);
proc.Close();
}
}
The exitcode I get is: -1066598274
Result variable is empty.
No exception is thrown
I am using Windows 2008 with IIS 7.0
Thanks in advance,
Ezequiel
Don't do this. This is just plain dirty and should not be done from ASP.NET
Write a windows service
Store the request in a queue
The service should poll the queue and process. If needed run the exe. It is suggested that the service stays in a different server.
Don't do this. This is very bad and not scalable and bad for the web server
Don't
Don't
Don't
protected void btnSubmit_Click(object sender, System.EventArgs e)
{
if (Page.IsValid)
{
litMessage.Visible = true;
System.Diagnostics.Process oProcess = null;
try
{
string strRootRelativePathName = "~/Application.exe";
string strPathName =
Server.MapPath(strRootRelativePathName);
if (System.IO.File.Exists(strPathName) == false)
{
litMessage.Text = "Error: File Not Found!";
}
else
{
oProcess =
new System.Diagnostics.Process();
oProcess.StartInfo.Arguments = "args";
oProcess.StartInfo.FileName = strPathName;
oProcess.Start();
oProcess.WaitForExit();
System.Threading.Thread.Sleep(20000);
litMessage.Text = "Application Executed Successfully...";
}
}
catch (System.Exception ex)
{
litMessage.Text =
string.Format("Error: {0}", ex.Message);
}
finally
{
if (oProcess != null)
{
oProcess.Close();
oProcess.Dispose();
oProcess = null;
}
}
}
}
If you use
proc.StartInfo.RedirectStandardOutput = true;
then you have to read the stream as the process executes, instead of before the call to
proc.WaitForExit();
Same goes for the standard error stream. See the MSDN docs for more detail.
You need to reorder the output reading at the end.
It expects you to read before the waitforexit() call, so you should have:
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
Response.Write(result + " - " + proc.ExitCode);
proc.WaitForExit();
proc.Close();
If the application you're trying to run is really a .NET application as you say, you may not need to run it in a separate process at all. Instead, you can take advantage of the fact that .NET executables are also assemblies. I don't think Visual Studio will let you reference assemblies that end in .exe, but the command-line compiler will.
I would try using the command-line compiler to create a wrapper assembly that simply references the executable assembly, and directly calls its Main() method, passing in a string array of any command-line parameters you would normally specify. The exit code, if any, will be an integer return value from the Main method. Then you can simply call your wrapper assembly from your ASP.NET app.
Depending on what the executable does, and how much it interacts with the console, this approach may not work at all. But if it does work for your case, it should perform much better than spinning up a separate process.
What i do is to have the executable called by a ms sql job.
The executable would be run as SQL server agent service account.
Create a new sql server job
Give it a name in the job property's general page
In the steps page, create a new step of type Operating system (CmdExec)
Speeify the command and click ok to save the job parameters
The new job can be called using EXEC msdb.dbo.sp_start_job #jobname, where #jobname is
the variable carrying the name of the job you want to start.
Note that when this job starts, the UI of the exe will be hidden and will not be displayed; but you can find it in your task manager.
I have employed this method in several applications especially time consuming operations that cannot be done on the web page.
You may need to set the proc.StartInfo.LoadUserProfile property to true so the administrator's user profile stuff is loaded into the registry (AFAIK this does not happen by default).
Also, it might be educational to run a 'hello world' program to see if the problem is with actaully creating the process or if the process itself is having problems running in the context it's given.
Finally, as a step in trying to narrow down where the problem might be, you might want to run the ASP.NET process itself with admin or system credentials to see if something in the permissions of the account the ASP.NET instance is running under is part of the problem (but please do this only for troubleshooting).
Use below code:
ProcessStartInfo info = new ProcessStartInfo("D:\\My\\notepad.exe");
info.UseShellExecute = false;
info.RedirectStandardInput = true;
info.RedirectStandardError = true;
info.RedirectStandardOutput = true;
//info.UserName = dialog.User;
info.UserName = "xyz";
string pass = "xyz";
System.Security.SecureString secret = new System.Security.SecureString();
foreach (char c in pass)
secret.AppendChar(c);
info.Password = secret;
using (Process install = Process.Start(info))
{
string output = install.StandardOutput.ReadToEnd();
install.WaitForExit();
// Do something with you output data
Console.WriteLine(output);
}