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

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 + "\"";

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 do I rename a file via batch using Process in c#

I have to rename multiple files on my server. For this I make a c# project in visual studio. (side info: this project has to do other stuff too)
Now I try to call a batch file from that project. This batch file has to rename a file using the old and the new filename.
Here is the code from the batch file:
#echo off
set FILENAME_OLD="%~1"
set FILENAME_NEW="%~nx2"
ren %FILENAME_OLD% %FILENAME_NEW%
set error=%errorlevel%
echo %error%
This is the code in my c# project:
process.StartInfo.FileName = location;
process.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\"", oldfilename, newfilename);
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
result = process.StandardOutput.ReadLine();
As result I always get 1. Which means that "ren" didn't work. What am i doing wrong here?
The filenames are all in a structure like this in my c# project: #"C:\test\test\test.bat"
EDIT:
I came somewhat closer to a solution. The problem was that I cant pass the double quotes as an argument. I need those double quotes as some of my filenames contain spaces.
How can I pass those filenames correctly to that batchfile?
I managed to fix the problem with on a in my opinion 'dirty' way:
//I changed newfilename so it's only the filename with extention and not the full path anymore.
string text = "\"" + oldfilename+ "\"" + " " + "\"" + newfilename;
System.IO.File.WriteAllText(#"c:\test\test.txt", text);
process.StartInfo.FileName = location;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
result = process.StandardOutput.ReadLine();
As you can see I wrote the arguments to a txt file so the quotes will be escaped.
The batchfile now is as simple as this:
set /p arguments=<c:\test\test.txt
ren %arguments%
echo %errorlevel%

"The system cannot find the file specified" error on process.Start();

I am trying to get the process respond as a string so I can use it in different place in my code, this is the solution that I have so far:
const string ex1 = #"C:\Projects\MyProgram.exe ";
const string ex2 = #"C:\Projects\ProgramXmlConfig.xml";
Process process = new Process();
process.StartInfo.WorkingDirectory = #"C:\Projects";
process.StartInfo.FileName = "MyProgram.exe ";
process.StartInfo.Arguments = ex2;
process.StartInfo.Password = new System.Security.SecureString();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
try
{
process.Start();
StreamReader reader = process.StandardOutput;
string output = reader.ReadToEnd();
}
catch (Exception exception)
{
AddComment(exception.ToString());
}
But when I'm running this I get:
"The system cannot find the file specified" error in process.Start(); without
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
The code runs fine but it just open console window and all the process response is trow there so I can't use it as string.
Does anyone know why I am getting this error or maybe a different solution to my problem?
I suspect the problem is that the filename you're specifying is relative to your working directory, and you're expecting Process.Start to look there when starting the process - I don't believe it works that way when UseShellExecute is false. Try just specifying the absolute filename of the process you want to start:
process.StartInfo.FileName = #"C:\Projects\MyProgram.exe";
Note that I've also removed the space from the end of the string you were assigning for the FileName property - it's entirely possible that was casuing the problem too.
For System32 access if you are trying to RUN an x86 Application on x64 then you must use the "Sysnative" keyword instead of "System32" in your filename.
EG: instead of:
C:\Windows\System32\whoiscl.exe
It should be:
C:\Windows\Sysnative\whoiscl.exe
Hope this helps someone

Exec batch file not run with space in project folder

I have a simple problem but I don't know how to handle this. That is: I have a simple batch file that remove all file in the folder (for example). I can run it in anywhere but I want to exec it by a application by C#. Everything is allright If the project folder doesn't contains spaces ("Example: C:\Project Test\test.bat" will be error" but "C:\ProjectTest\test.bat" is done").
Below is my source code to run (I say it again: It only error if project folder contain space in folder names). Not error when run file batch if project folder not have space.
Process myProcess = new Process();
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.Arguments = "D:\\prepare.bat";
myProcess.StartInfo.WorkingDirectory = "D:\\";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
//myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.Start();
StreamReader myStreamReader = myProcess.StandardOutput;
string myString = myStreamReader.ReadLine();
MessageBox.Show(myProcess.StartInfo.Arguments + " " + myString);
myProcess.WaitForExit();
Thanks you.
Try putting script path in quotes:
myProcess.StartInfo.Arguments = "\"D:\\Project Test\\prepare.bat\"";
Enclose your arguments in quotes like this:
myProcess.StartInfo.Arguments = "\"C:\\Project Test\\test.bat\""
or
myProcess.StartInfo.Arguments = #"\"C:\Project Test\test.bat\""
When passed to cmd the arguments must be quoted.
instead of "C:\Project Test\test.bat" use "\"C:\Project Test\test.bat\""

Passing file paths to a batch file

I'm calling a .bat file to XCOPY a folder. Is there anyway to pass the file name and the destination into the batch file?
My .bat file
XCOPY %1 %2
pause
The code I'm using to call the .bat is this:
process.Start(#"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat");
I've tried this code
process.Start(#"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat" , copyfrom copyto);
As i've used that before for shutting down my comp, but it doesn't work with this.
Thanks
Update
process.StartInfo.FileName = #"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat";
process.StartInfo.Arguments = copyFrom.ToString();
process.StartInfo.Arguments = copyTo.ToString();
process.Start();
That is the code I'm using but It doesn't work. I'm getting this from the XCOPY screen:
So it doesn't look like its taking the full file paths. copyto and copyfrom are variables that contain the paths.
UPDATE
Using azhrei's code:
String batch = #"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat";
String src = #"C:\Tricky File Path\Is Here\test1.txt";
String dst = #"C:\And\Goes Here\test2.txt";
String batchCmd = String.Format("\"{0}\" \"{1}\" \"{2}\"", batch, src, dst);
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = String.Format("/k \"echo {0}\"", batchCmd);
process.Start();
I'm getting this output:
Which isn't actually copying the file.
you can use Arguments property
Process proce = new Process();
proce.StartInfo.FileName = "yourfile.exe";
proce.StartInfo.Arguments = ..;
proce.Start();
Article : http://www.c-sharpcorner.com/UploadFile/jawedmd/xcopy-using-C-Sharp-to-copy-filesfolders/
Replace it with this,
var process = new Process();
process.StartInfo.FileName = #"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat";
process.StartInfo.Arguments = // my arguments
process.Start();
A better option would be to replace what your XCOPY.BAT file is doing with the equivalent calls in System.IO (you get error handling then).
You're starting a batch file - you'll need to use cmd.exe
Surround each argument with " (needed if the argument has spaces).
String batch = #"C:\Documents and Settings\cmolloy\My Documents\Test\XCOPY.bat";
String src = #"C:\Tricky File Path\Is Here\test1.txt";
String dst = #"C:\And\Goes Here\test2.txt";
String batchCmd = String.Format("\"{0}\" \"{1}\" \"{2}\"", batch, src, dst);
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = String.Format("/k \"{0}\"", batchCmd);
process.Start();
If your batch file literally xcopies and nothing else, then you can just replace cmd.exe with xcopy.exe and remove the /k + batch.
Pass it parameters?
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/percent.mspx?mfr=true

Categories