Using command prompt to delete specific files within downloads folder - c#

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

Related

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

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.

Activating conda environment from c# code (or what is the differences between manually opening cmd and opening it from c#?)

I want to run a gpu accelerated python script on windows using conda environment (dlwin36).
I’m trying to activate dlwin36 and execute a script:
1) activate dlwin36
2) set KERAS_BACKEND=tensorflow
3) python myscript.py
If I manually open cmd on my machine and write:"activate dlwin36"
it works.
But when I try opening a cmd from c# I get:
“activate is not recognized as an internal or external command, operable program or batch file.”
I tried using the following methods:
Command chaining:
var start = new ProcessStartInfo();
start.FileName = "cmd.exe";
start.Arguments = "/c activate dlwin36&&set KERAS_BACKEND=tensorflow&&python myscript.py";
Process.Start(start).WaitForExit();
(I’ve tested several variations of UseShellExecute, LoadUserProfile and WorkingDirectory)
Redirect standard input:
var commandsList = new List<string>();
commandsList.Add("activate dlwin36");
commandsList.Add("set KERAS_BACKEND=tensorflow");
commandsList.Add("python myscript.py");
var start = new ProcessStartInfo();
start.FileName = "cmd.exe";
start.UseShellExecute = false;
start.RedirectStandardInput = true;
var proc = Process.Start(start);
commandsList.ForEach(command => proc.StandardInput.WriteLine(command));
(I’ve tested several variations of LoadUserProfile and WorkingDirectory)
In both cases, I got the same error.
It seems that there is a difference between manually opening cmd and opening it from c#.
The key is to run activate.bat in your cmd.exe before doing anything else.
// Set working directory and create process
var workingDirectory = Path.GetFullPath("Scripts");
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
UseShellExecute = false,
RedirectStandardOutput = true,
WorkingDirectory = workingDirectory
}
};
process.Start();
// Pass multiple commands to cmd.exe
using (var sw = process.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
// Vital to activate Anaconda
sw.WriteLine("C:\\PathToAnaconda\\anaconda3\\Scripts\\activate.bat");
// Activate your environment
sw.WriteLine("activate your-environment");
// Any other commands you want to run
sw.WriteLine("set KERAS_BACKEND=tensorflow");
// run your script. You can also pass in arguments
sw.WriteLine("python YourScript.py");
}
}
// read multiple output lines
while (!process.StandardOutput.EndOfStream)
{
var line = process.StandardOutput.ReadLine();
Console.WriteLine(line);
}
You need to use the python.exe from your environment. For example:
Process proc = new Process();
proc.StartInfo.FileName = #"C:\path-to-Anaconda3\envs\tensorflow-gpu\python.exe";
or in your case:
start.Arguments = "/c activate dlwin36&&set KERAS_BACKEND=tensorflow&&\"path-to-Anaconda3\envs\tensorflow-gpu\python.exe\" myscript.py";
I spent a bit of time working on this and here's the only thing that works for me: run a batch file that will activate the conda environment and then issue the commands in python, like so. Let's call this run_script.bat:
call C:\Path-to-Anaconda\Scripts\activate.bat myenv
set KERAS_BACKEND=tensorflow
python YourScript.py
exit
(Note the use of the call keyword before we invoke the activate batch file.)
After that you can run it from C# more or less as shown above.
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "cmd.exe";
start.Arguments = "/K c:\\path_to_batch\\run_script.bat";
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
start.WorkingDirectory = "c:\\path_to_batch";
string stdout, stderr;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
stdout = reader.ReadToEnd();
}
using (StreamReader reader = process.StandardError)
{
stderr = reader.ReadToEnd();
}
process.WaitForExit();
}
I am generating the batch file on the fly in C# to set the necessary parameters.
If this is gonna help anyone in the future. I found that you must run the activation from C:\ drive.

Other way to put a path in quotes when using DirectoryInfo?

I'm currently working with reg.exe and I'm creating a process with reg.exe as the Process.FileName.
When I try to execute reg.exe like following
REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS D:\\Backups\\Test.reg
everthing works fine.
But as soon as I try to execute it like this
REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS D:\\Backups\\Backup folder 1\\Test.reg
nothing happens - and I know why! The target path isn't put in quotes. As soon as I do that everything works fine again.
My problem now is that I'm handling all my file and folder paths as instances of DirectoryInfo. When I pass the path with quotes as a string, e.g. like that
DirectoryInfo targetFolder = new DirectoryInfo("\"D:\\Backups\\Backup folder 1\\Test.reg\"")
I instantly receive an exception telling me that the given path's format is not supported.
Is there any way to put the path in quotes and still work with DirecotryInfo?
I really need to put my path in quotes - otherwise the command won't work.
Here's some example code:
DirectoryInfo backupPath = new DirectoryInfo("D:\\Backups\\Backup folder 1\\Test.reg");
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "reg.exe";
startInfo.CreateNoWindow = true;
startInfo.Arguments = "REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS " + backupPath.FullName;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
When I run this code, nothing happens - nor errors or exceptions. The .reg file itself isn't created either.
When I try to run it like this
DirectoryInfo backupPath = new DirectoryInfo("\"D:\\Backups\\Backup folder 1\\Test.reg\"");
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "reg.exe";
startInfo.CreateNoWindow = true;
startInfo.Arguments = "REG EXPORT HKLM\\SOFTWARE\\Intel\\IntelAMTUNS " + backupPath.FullName;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
I'm getting a System.NotSupportedException telling me "The given path's format is not supported." But I actually need to put the path in quotes - otherwise the command itself won't work...
You are adding quotes in the wrong place: constructor of DirectoryInfo will strip them anyway to normalize the path, so you can skip adding them:
var backupPath = new DirectoryInfo("D:\\Backups\\Backup folder 1\\Test.reg");
You can force quotes around the path when you add backupPath.FullName to the arguments, like this:
startInfo.Arguments = "REG EXPORT HKLM\SOFTWARE\Intel\IntelAMTUNS \"" + backupPath.FullName + "\"";

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);
}

Categories