How can I run Python script with commands in C# button - c#

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.

Related

Using command prompt to delete specific files within downloads folder

I'm trying to use the following code to delete specific files from my downloads folder -
var process = new Process();
var startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Normal,
FileName = "cmd.exe",
RedirectStandardInput = true,
UseShellExecute = false
};
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine("cd C://users/%username%/downloads");
process.StandardInput.WriteLine("del /f Secci*");
When debugging the code - the command prompt window flashes open but then instantly closes (even though it didn't specify for it to be hidden in the code) so I'm struggling to see if it's even managing to CD into the correct directory. Currently the file(s) are not being deleted from the downloads folder either. This is part of a 'Before Test' class within our test automation project. Would be great if someone could give some suggestions on why this might not be working?
For deleting in cmd prompt. Try this
string file = "Secci*";
Process process = new Process();
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.Start();
process.StandardInput.WriteLine("cd C://users/%username%/downloads");
process.StandardInput.WriteLine(string.Format("del \"{0}\"", file));
If you are trying to use System.IO, Try this.
using System.IO;
string file = "Secci*";
//Because "SpecialFolder" doesn't have Downloads in it, this is my workaround. There may be better ones out there.
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = path.Replace("Documents", "Downloads");
string[] List = Directory.GetFiles(path, file);
foreach (string f in List)
{
File.Delete(f);
}
You can get all the files by enumerating the directory.
Once you have the files that match your criteria, you can iterate over them and perform actions on them.
var dir = new DirectoryInfo("C://users/%username%/downloads");
foreach (var file in dir.EnumerateFiles("Secci*")) {
file.Delete();
}
https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.enumeratefiles?view=netframework-4.7.2

How can i set the directory to where my application was installed?

I used innosetup to install my application.
All the files for example are in program files\test
In the directory i have the exe file of my program and also ffmpeg.exe
Now in my code i did :
class Ffmpeg
{
NamedPipeServerStream p;
String pipename = "mytestpipe";
byte[] b;
System.Diagnostics.Process process;
string ffmpegFileName;
string workingDirectory;
public Ffmpeg()
{
workingDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + #"\workingDirectory";
ffmpegFileName = #"\ffmpeg.exe";
if (!Directory.Exists(workingDirectory))
{
Directory.CreateDirectory(workingDirectory);
}
ffmpegFileName = workingDirectory + ffmpegFileName;
Logger.Write("Ffmpeg Working Directory: " + ffmpegFileName);
}
public void Start(string pathFileName, int BitmapRate)
{
try
{
string outPath = pathFileName;
Logger.Write("Output Video File Directory: " + outPath);
Logger.Write("Frame Rate: " + BitmapRate.ToString());
p = new NamedPipeServerStream(pipename, PipeDirection.Out, 1, PipeTransmissionMode.Byte);
b = new byte[1920 * 1080 * 3]; // some buffer for the r g and b of pixels of an image of size 720p
ProcessStartInfo psi = new ProcessStartInfo();
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.FileName = ffmpegFileName;
psi.WorkingDirectory = workingDirectory;
Thep roblem is that the directory workingDirectory not contain the ffmpeg.exe after installation . so if the user will run first time the program after installation the file will be missing .
I added the ffmpeg.exe to my project and set it to : Content and Copy always
What i want to do is that somehow to set the workingDirectory to the place where the user was installing the program if it's program file or any other directory .
Or to set the workigDirectory to the file ffmpeg.exe i already added to the project.
The problem is after installation the user will run the program and the directory workingDirectory will be empty .
if the file ffmpeg.exe is installed in the same directory where the assembly that calls it resides, then your could write:
string fullPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string installDirectory = Path.GetDirectoryName( fullPath );
However if you really want to copy that file from the installed directory to the Application.LocalUserAppDataPath
// Assuming that the LocalUserAppDataPath has already been created
string destDirectory = Path.Combine(Application.LocalUserAppDataPath, "workingDirectory");
File.Copy(Path.Combine(installDirectory, "ffmpeg.exe"),
Path.Combine(destDirectory, "ffmpeg.exe"), true);
but then, why you don't search the functionality of InnoSetup to discover how to place the ffmpeg.exe file in the workingDirectory during setup? That will solve all your issues here.
1- You should create a registry key that can store the installation path and path of any other folder that your application needs. Check this question on how to do that: How to write install path to registry after install is complete with Inno setup
2- Read the registry settings at application startup. Use those paths.
You can use Application.StartupPath to reference the folder path where are your main executable and ffmpeg.exe
Application.StartupPath
Gets the path for the executable file that started the application,
not including the executable name.
http://msdn.microsoft.com/en-us/library/system.windows.forms.application.startuppath.aspx
And then if you need it... copy the ffmpeg.exe to the working directory that you choose.. though I think its not a good idea...
File.Copy(Source, Target)
http://msdn.microsoft.com/en-us/library/c6cfw35a.aspx
string destDirectory = Path.Combine(Application.LocalUserAppDataPath, "workingDirectory");
string ffmpegDestPath = Path.Combine(destDirectory, "ffmpeg.exe");
string ffmpegSrcPath = Path.Combine(Application.StartupPath, "ffmpeg.exe");
if (!File.Exist(ffmpegDestPath)) {
if (!Directory.Exists(destDirectory)) Directory.Create(destDirectory);
File.Copy(ffmpegSrcPath , ffmpegDestPath );
}

Add to my solution folder with exe file that i want to run

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.

Directory.GetCurrentDirectory

I've written a program that checks if it is in a specific folder;
if not, it copies itself into that folder,run the copied program and exit.
but the problem is when I call
Directory.GetCurrentDirectory();
in the copied program(only when It runs by the first one) I get the directory of the first program not the copied one.
What's the problem here?
the code:
if(Directory.GetCurrentDirectory()!=dir)
{
File.Copy(Application.ExecutablePath,dir+name);
System.Diagnostics.Process.Start(dir+#"\"+name);
System.Environment.Exit(System.Environment.ExitCode);
}
i summarized my codes.
You have to use the WorkingDirectory on the processinfo, no need for copying the files.
if(Directory.GetCurrentDirectory()!=dir)
{
string exepath = Path.Combine(dir,name);
ProcessStartInfo processStartInfo = new ProcessStartInfo();
process.StartInfo.FileName = exepath;
processStartInfo.WorkingDirectory = dir;
//Set your other process info properties
Process process = Process.Start(processStartInfo);
System.Environment.Exit(System.Environment.ExitCode);
}

C#: How would I execute this command line directly to java.exe?

I am writing a program that needs to run a java.jar server. I need to run the process directly so I can rewrite the output to a textbox and all-in-all have complete control of it. I tried just doing it through CMD.exe, but that wouldnt work because CMD.exe would just call a new process java.exe and I wouldn't have control of it. I need to call java.exe directly so I can have the control and get the output. Can any of you tell me how to convert this command so I could create a process in C# and call it?
I need this CMD command converted:
"java -Xmx1024m -cp ./../libs/*;l2jserver.jar net.sf.l2j.gameserver.GameServer"
into
a command line I can put into the Process.Arguments so I can call Java.exe directly.
I've tried to do it... and it just won't work.
I've been looking at this for hours and hours... please someone help!
Part of the problem might be that despite what the Framework documentation says using Process doesn't always resolve things against the PATH environment variable properly. If you know the name of the folder Java is in then use the full path to Java.exe, otherwise use a function like the following:
private void LocateJava()
{
String path = Environment.GetEnvironmentVariable("path");
String[] folders = path.Split(';');
foreach (String folder in folders)
{
if (File.Exists(folder + "java.exe"))
{
this._javadir = folder;
return;
}
else if (File.Exists(folder + "\\java.exe"))
{
this._javadir = folder + "\\";
return;
}
}
}
It's somewhat hacky but it will find java.exe provided the Java Runtime is installed and it's folder is in the windows PATH variable. Make a call to this function the first time your program needs to find Java and then subsequently start Java using the following:
//Prepare the Process
ProcessStartInfo start = new ProcessStartInfo();
if (!_javadir.Equals(String.Empty)) {
start.FileName = this._javadir + "java.exe";
} else {
start.FileName = "java.exe";
}
start.Arguments = "-Xmx1024m -cp ./../libs/*;l2jserver.jar net.sf.l2j.gameserver.GameServer";
start.UseShellExecute = false;
start.RedirectStandardInput = true;
start.RedirectStandardOutput = true;
//Start the Process
Process java = new Process();
java.StartInfo = start;
java.Start();
//Read/Write to/from Standard Input and Output as required using:
java.StandardInput;
java.StandardOutput;

Categories