C#: Looping Through a Directory Calling an External Process - c#

I have the C# code below, used to input each file in a directory, run an XQuery process on it, and output each file as an XML file. The code calls the SAXON XQuery processor. Note: the code works now but it only processes the first file in the directory. The second, third, etc. output files from the input directory come back as empty XML files. Question: how do I modify the code to process all the files (not just the first one) in the input directory?
public void OpenWithArguments(string t)
{
string sourceDir = t;
string [] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
Process process = new Process();
process.StartInfo.FileName = #"C:\Program Files\Java\jdk6\bin\java";
process.StartInfo.CreateNoWindow = true;
process.StartInfoArguments =
#" -cp C:\mydir\saxon9he.jar net.sf.saxon.Query -o:C:\myOutPutFiles\" +
Path.GetFileNameWithoutExtension(fileName) +
#".xml C:\myQueries\myquery.xquery input=" +
Path.GetFileNameWithoutExtension(fileName);
process.Start();
process.Close();
}
}

Try adding process.WaitForExit() after you start it.

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.

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%

How to catch %ERRORLEVEL% when running Psexec.exe in C#, save to log file

I am using psexec.exe to install some software on a large amount of computers. I would like to be able to catch the %ERRORLEVEL% (or its c# equivalent) and write them to a TXT file. ( cmd.exe exited on 6440-nbpb00f51w with error code 0.)
After extensive research, I am finding several possibilities. My end-goal will be to have a .CSV file. Each row would have the computer name and the output of the psexec command. Using this data I will be able to determine which computers the update was successful on.
string[] pcnamearray = new string[] {"COMPUTERNAME1", "COMPUTERNAME2"};
foreach (string i in pcnamearray)
{
Process p = new Process();
string psexeclaunch = "psexec.exe";
p.StartInfo.FileName = psexeclaunch;
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.UseShellExecute = true;
p.StartInfo.CreateNoWindow = false;
string arg = "/silent";
p.StartInfo.Arguments = #" -i \\" + i + #" -u mydomain\admin -p mypassword -h -e cmd.exe /c start \\networkserver\sw\myfile.exe" + arg;
p.Start();
}
I am not here looking for someone to write the code for me. I am here to ask people for their advice, or past experiences with this. I know there are several different methods available. Ideally, I would prefer to have a short sweet line for each result, but if i have to take the entire output and use macros to shave them down to a more readable form, that is fine too.
So far, I have tried:
Console.WriteLine(p.StandardOutput.ReadToEnd());
And...
System.IO.File.WriteAllLines(#"C:\Users\areu2447\Desktop\UpdateDAT\Final\out.txt", lines);
And...
FileStream filestream = new FileStream(#"C:\Users\areu2447\Desktop\UpdateDAT\Final\out.txt", FileMode.Append);
var streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
The last one seems to me like the best one but cannot seem to get it to work. I have tried including it in my foreach loop, but file is in use by another process, so after looking into it i found that it needed to be on its own. Even with it alone, i still cannot get it to work.
Please help/advise!
I was able to get it to actaully modify my TXT file, even though there was nothing added to it, by using the following:
System.IO.StreamReader reader = p.StandardOutput;
String sRes = reader.ReadToEnd();
StreamWriter SW;
SW = File.CreateText(#"C:\Users\areu2447\Desktop\UpdateDAT\Final\out.txt");
SW.WriteLine(sRes);
SW.Close();
Console.WriteLine("File Created Successfully");
reader.Close();
I would recommend using System.Management.Automation to create a PowerShell pipeline and run the script in process.
Executing PowerShell scripts from C#

unzip file in C# via Winzip and its cmd extension

so I have a small chunk of code that detects files in a folder and systematically zips them after they become a certain age. I'm now working on a piece of code to unzip files of a certain date-range at user request for use in the software.
My issue is that the command-line string to zip files works great, but the unzip does not... below is the excerpt of code showing how I unzip, please let me know what I should do differently to ensure unzipping. thanks!
private void UnZipFile()
{
if (myRecord == null)
{
if (File.Exists(zipInfo.FullName))
{
Process LogUnzipper = new Process();
//32-bit system
if (File.Exists("c:\\Program Files\\WinZip\\WZZIP.exe"))
{
//WZZIP.exe being the WinZip executable
LogUnzipper.StartInfo.FileName = "c:\\Program Files\\WinZip\\WZZIP.exe";
}
//64-bit system
else if (File.Exists("c:\\Program Files (x86)\\WinZip\\WZZIP.exe"))
{
//WZZIP.exe being the WinZip executable
LogUnzipper.StartInfo.FileName = "c:\\Program Files (x86)\\WinZip\\WZZIP.exe";
}
//here is where I think I'm screwing up something..
string action = "-e " + "\"" + zipInfo.FullName + "\"" + " \"" + zipInfo.DirectoryName + "\"";
//happen in background
LogUnzipper.StartInfo.CreateNoWindow = true;
LogUnzipper.StartInfo.UseShellExecute = false;
LogUnzipper.StartInfo.Arguments = action;
LogUnzipper.Start();
while (!LogUnzipper.HasExited)
{
LogUnzipper.WaitForExit(500);// 1/2 sec
}
//adding break point at this line yields no unzipped Log file :(
}
...
my thoughts are that I'm somehow calling the cmd wrong in string action? even though if I test it in a windows command prompt that's correct formatting.
***it should be noted that ZipInfo.FullName is something along the ex: "C:\Users\16208\Software\Beta\logs\6_2013\Log_10AM_to_11AM.zip" as far as formmat, so I am giving an accurate path to the zipped Item.
You can use some free and open-source .Net library for zipping and unzipping (as SLaks suggested). For example DotNetZip.
using (ZipFile decompress = ZipFile.Read(ZipFilePath))
{
foreach (ZipEntry e in decompress)
{
e.Extract(TargetPath, ExtractExistingFileAction.OverwriteSilently);
}
}
As for your code, waiting half a second may not be enough for unzipping to complete. Also you can try running your unzip command in a command line and check the output.
If you have WinZip installed try this:
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", #"/c start winzip32 -e " + fileName + #" C:\SomeDirectory");
rocStartInfo.UseShellExecute = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
Where fileName is the full path to your *.rar file.

Categories