So I want to run a powershell script inside of a c# project. The powershell file would be located in a folder inside the project. I am just not sure how to reference that file from c# to run it.
Please do a google search before you ask here
https://learn.microsoft.com/da-dk/archive/blogs/kebab/executing-powershell-scripts-from-c
https://duanenewman.net/blog/post/running-powershell-scripts-from-csharp/
var ps1File = #"C:\my script folder\script.ps1";
var startInfo = new ProcessStartInfo()
{
FileName = "powershell.exe",
Arguments = $"-NoProfile -ExecutionPolicy unrestricted -file \"{ps1File}\"",
UseShellExecute = false
};
Process.Start(startInfo);
Related
I'm trying to run a curl command from a C# program. My code is below. When I run the code below, I get an exception that the file is not found. I want to be able to do this but I do not want to use a batch file as a parameter for the filename. That is because the arguments for my curl command are variable based upon other conditions in the C# code. My variable strCmdText has the arguments for the curl command (the source and destination files). There are other examples of this on Stackoverflow, but they all use a batch file which I'm trying to avoid.
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "C:\\Windows\\System32\\curl.exe";
p.StartInfo.Arguments = strCmdText;
p.StartInfo.UseShellExecute = false;
p.Start();
p.WaitForExit();
I changed my code to the following:
System.Diagnostics.ProcessStartInfo p = new
System.Diagnostics.ProcessStartInfo();
p.UseShellExecute = true;
p.WorkingDirectory = "C:\\Windows\\System32\\";
p.FileName = "curl.exe";
p.ErrorDialog = true;
p.CreateNoWindow = true;
System.Diagnostics.Process.Start(p);
From a DOS prompt, curl does exist in this directory. But I still get the curl not found message.
Something has to be strange with the path here. When I put a break point in though, and view the Environment class, System32 is in the path.
Curl is available at the location: C:\Windows\System32\curl.exe
That only leaves the source file to be the culprit of a "File not found" issue.
As you're launching curl through a process, ensure that your paths are escaped properly in your startup arguments.
Alternatively, you could launch curl through cmd (through a process), you can try with the following, changing the command-line arguments from --help to suit your desired action.
string script = $"\"C:\\Windows\\System32\\curl.exe\" --help";
Process process = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = "cmd",
Arguments = script
}
};
process.Start();
Please note that this is in principle, essentially using a batch file as it's just throwing some commands into a cmd.
I had the exact same problem. Just delete curl.exe from System32 and place it on another folder (dont't forget the dependences, dlls, etc.).
Then in the line
p.StartInfo.FileName = "C:\\Windows\\System32\\curl.exe";
Overwrite "C:\\Windows\\System32\\curl.exe" to "C:\\NEW PATH\\curl.exe".
Note: You MUST delete it from System32. If you just copy to the new location it will still don't work.
I have my script written in Python and GUI for it in C#. That is why I'd like to run Python from C# (I have to use the original Python version because of various modules which i.e. IronPython does not support). To secure the script I embedded it into the .exe file. Now, how can I get the script path?
My previous code:
string python = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"\python\python.exe";
// NOW it obviously does not work
string scriptPath = #"C:\..\script.py";
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcessStartInfo.Arguments = scriptPath;
Process myProcess = new Process();
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
Assembly.GetExecutingAssembly().GetManifestResourceStream(...)
won't be useful here because I don't want stream (or do I?), just the path.
If the script is an embedded resource (How to read embedded resource text file), you could read it as string and use the -c parameter of python.exe
Lets say I have this super Python script that needs to run cv2 in the future...
import cv2
def method():
print("Hello")
parameter = "l"
return "OOPS"
method()
And in C# something like this.
Process p = new Process();
p.StartInfo = new ProcessStartInfo(#"D:\Programming\Python\python.exe", fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
But this does throw an error "ImportError: DLL load failed". Alright seems like it is lookin in wrong directories for libraries since I have about 4 Python interpreters. Follows quick fix.
string path = #"D:\Programming\Python;" + Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable("PATH", path, EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONHOME", #"D:\Programming\Python;", EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONPATH ", #"D:\Programming\Python\Lib; D:\Programming\Python\DLLs", EnvironmentVariableTarget.Process);
string fileName = #"..\Python\hello.py";
Process p = new Process();
p.StartInfo = new ProcessStartInfo(#"D:\Programming\Python\python.exe", fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
Import DLL is fixed now, but another wild bug appeared named,
Fatal Python error: initfsencoding: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'
At this point I am lost and dont know what should I do next... any ideas are welcome, have a nice day.
UPDATE:
Deleted all other python interpretors aside from anaconda and one virtual env and tried following:
Run Python script from Visual Studio Code with given interpretor, works fine.
Run it from Anaconda prompt, aswell.
Added manually to system environment variables
PATH=D:\Programming\Python
PYTHONHOME=D:\Programming\Python
PYTHONPATH=D:\Programming\Python\Lib;D:\Programming\Python\DLLs;D:\Programming\Python\Lib\site-packages
So now I can successfully call "python" from cmd, like that and check version, the virtual env is python 3.6 and this is the right one.
Python is correct
But this is where all the fun begins you would expect "hello" in your console...
hell incarnate
Did not find correct answer to this problem, but discovered workaround in p2exe or pyinstaller.
Simply call pyinstaller.py --onefile xx.py and create exe file and pass that into process.
I have an application that generates some files. Once the files are generated, i want to then perform some Git commands to start a local repository. I have spent a few days on multiple solutions and endless googling but i can't get this to work as expected.
If i manually kick off the .exe, locally or on a server, it works perfectly. However, when the application(MVC) calls the .exe it doesn't work locally or on a server. I will provide the code that calls the .exe itself and then what the .exe code is doing.
MVC call to run .exe
//Call git exe
var processInfo = new ProcessStartInfo()
{
Arguments = Arg1 + " " + Arg2,
UseShellExecute = false,
FileName = #"C:\Foo.exe"
};
var process = new Process()
{
StartInfo = processInfo
};
process.Start();
process.WaitForExit();
This .exe gets launched without issue so this part is working i think. I checked it via task manager.
Git command execution
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
UseShellExecute = false,
WorkingDirectory = Properties.Settings.Default.OutPutDirectory
},
};
process.Start();
using (var writer = process.StandardInput)
{
writer.WriteLine("git init");
writer.WriteLine("git add --all");
writer.WriteLine("git commit --author=\"" + ParseUserNameFromEmail() + " <" + _userEmailAddress + ">\" -m \"Initial Commit\"");
}
If i execute this part manually from the cmd prompt it works perfect on both local and server. But as soon as this .exe is called from an MVC app, it runs but the git repo isn't created as expected. I am at a total lost. I have tried running the process with my creds and a service account. I have also tried capturing the output in hope to shed light on what the issue could be but it's just empty on error and output redirects :(.
after clicking on button in asp.net application process.start() runs edmgen tool with arguments. And I catch error :
var cs =ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
string myArgs="/mode:fullgeneration /c:\""+cs+"\" /project:nwd /entitycontainer:SchoolEntities /namespace:SchoolModel /language:CSharp ";
string filename= GetFrameworkDirectory() + "\\EdmGen.exe";
ProcessStartInfo startInfo = new ProcessStartInfo(filename,myArgs);
startInfo.UseShellExecute = false;
//startInfo.RedirectStandardError = true;
Process myGenProcess = Process.Start(startInfo);
//genInfo.Text = myGenProcess.StandardError.ReadToEnd();
How to fix this?
You need to pass the full path to a folder that you have write access to for the output.
Well the error indicates that you don't have access to "C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\nwd.ssdl".
Check that your process has the necessary permissions on the file and all the folders up the tree.