I am making a program that seeks out secured PDFs in a folder and converting them to PNG files using ImageMagick. Below is my code.
string WorkDir = #"C:\Users\rwong\Desktop\TestFiles";
Directory.SetCurrentDirectory(WorkDir);
String[] SubWorkDir = Directory.GetDirectories(WorkDir);
foreach (string subdir in SubWorkDir)
{
string[] filelist = Directory.GetFiles(subdir);
for(int f = 0; f < filelist.Length; f++)
{
if (filelist[f].ToLower().EndsWith(".pdf") || filelist[f].EndsWith(".PDF"))
{
PDFReader reader = new Pdfreader(filelist[f]);
bool PDFCheck = reader.IsOpenedWithFullPermissions;
reader.CLose();
if(PDFCheck)
{
//do nothing
}
else
{
string PNGPath = Path.ChangeExtension(filelistf], ".png");
string PDFfile = '"' + filelist[f] + '"';
string PNGfile = '"' + PNGPath + '"';
string arguments = string.Format("{0} {1}", PDFfile, PNGfile);
ProcessStartInfo startInfo = new ProcessStartInfo(#"C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe");
startInfo.Arguments = arguments;
Process.Start(startInfo);
}
}
}
I have ran the raw command in command prompt and it worked so the command isn't the issue. Sample command below
"C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe" "C:\Users\rwong\Desktop\TestFiles\Test_File File_10.PDF" "C:\Users\rwong\Desktop\TestFiles\Test_File File_10.png"
I looked around SO and there has been hints that spaces in my variable can cause an issue, but most of those threads talk about hardcoding the argument names and they only talk about 1 argument. I thought adding double quotes to each variable would solve the issue but it didn't. I also read that using ProcessStartInfo would have helped but again, no dice. I'm going to guess it is the way I formatted the 2 arguments and how I call the command, or I am using ProcessStartInto wrong. Any thoughts?
EDIT: Based on the comments below I did the extra testing testing by waiting for the command window to exit and I found the following error.
Side note: I wouldn't want to use GhostScript just yet because I feel like I am really close to an answer using ImageMagick.
Solution:
string PNGPath = Path.ChangeExtension(Loan_list[f], ".png");
string PDFfile = PNGPath.Replace("png", "pdf");
string PNGfile = PNGPath;
Process process = new Process();
process.StartInfo.FileName = #"C:\Program Files\ImageMagick-6.9.2 Q16\convert.exe";
process.StartInfo.Arguments = "\"" + PDFfile + "\"" +" \"" + PNGPath +"\""; // Note the /c command (*)
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.Start();
//* Read the output (or the error)
string output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
string err = process.StandardError.ReadToEnd();
Console.WriteLine(err);
process.WaitForExit();
It didn't like the way I was formatting the argument string.
This would help you to run you command in c# and also you can get the result of the Console in your C#.
string WorkDir = #"C:\Users\rwong\Desktop\TestFiles";
Directory.SetCurrentDirectory(WorkDir);
String[] SubWorkDir = Directory.GetDirectories(WorkDir);
foreach (string subdir in SubWorkDir)
{
string[] filelist = Directory.GetFiles(subdir);
for(int f = 0; f < filelist.Length; f++)
{
if (filelist[f].ToLower().EndsWith(".pdf") || filelist[f].EndsWith(".PDF"))
{
PDFReader reader = new Pdfreader(filelist[f]);
bool PDFCheck = reader.IsOpenedWithFullPermissions;
reader.CLose()l
if(!PDFCheck)
{
string PNGPath = Path.ChangeExtension(filelistf], ".png");
string PDFfile = '"' + filelist[f] + '"';
string PNGfile = '"' + PNGPath + '"';
string arguments = string.Format("{0} {1}", PDFfile, PNGfile);
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.EnableRaisingEvents = true;
p.StartInfo.CreateNoWindow = true;
p.startInfo.FileName = "C:\Program Files\ImageMagick-6.9.2-Q16\convert.exe";
p.startInfo.Arguments = arguments;
p.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
//You can receive the output provided by the Command prompt in Process_OutputDataReceived
p.Start();
}
}
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
string s = e.Data.ToString();
s = s.Replace("\0", string.Empty);
//Show s
Console.WriteLine(s);
}
}
Related
I'm executing a jar file from a c# process. This is how I start the process and redirect the Input & Output. Problem indicated at the bottom!
Process process = new Process();
process.EnableRaisingEvents = false;
if (isLinux)
{
process.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory() + "/Servers/" + server.ServerLocation + "/";
}
else
{
process.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory() + "\\Servers\\" + server.ServerLocation + "\\";
}
process.StartInfo.FileName = "java";
process.StartInfo.Arguments = "-Xms" + server.AllocatedRam + "M -Xmx" + server.AllocatedRam + "M -jar " + '"' + path + '"';
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
LogController.Notice("Server Starting", server.Name);
proc = process;
process.Start();
if (Write.ContainsKey(server.ID))
{
Write.Remove(server.ID);
Write.Add(server.ID, process.StandardInput);
}
else
{
Write.Add(server.ID, process.StandardInput);
}
if (Output.ContainsKey(server.ID))
{
Output.Remove(server.ID);
Output.Add(server.ID, process.StandardOutput);
}
else
{
Output.Add(server.ID, process.StandardOutput);
}
Dictionaries
public static Dictionary<string, StreamWriter> Write = new Dictionary<string, StreamWriter>();
public static Dictionary<string, StreamReader> Output = new Dictionary<string, StreamReader>();
Executing command without closing writer
StreamWriter w = ServerController.Write[ID];
w.Write(Command.command);
w.Flush();
^ Flushing this will not execute the write. If I dispose the writer then I cannot execute more than 1 command. The writer has to always be open for writes and be able to execute the write but flushing does not work.
I am trying to open my .exe "application" with 2 arguments. When I write the command line myself without " " it don't want to work. When I write the command line using "C:/Path" "A" "B" it does work.
How do I fix this?
if(element.SaveType == "1")
{
DirectoryInfo srcDir = new DirectoryInfo((string)element.SourcePath);
DirectoryInfo dstDir = new DirectoryInfo((string)element.DestinationPath);
if (element.didEncrypt == true)
{
if (Directory.GetFiles(srcDir.FullName, ((string)element.EncryptExt)).Length == 0)
{
string pat = System.IO.Path.Combine(#"C:\Users\Client Fractal\source\repos\CryptoSoft\CryptoSoft\bin\Debug\netcoreapp3.0\CryptoSoft.exe");
Process p = new Process();
p.StartInfo.FileName = pat;
p.StartInfo.Arguments = srcDir.FullName + dstDir.FullName; // source / target;
Console.WriteLine(p.StartInfo.Arguments);
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
}
}
}
Command-line arguments are space-character delimited, so you'd need to insert a space character or your arguments will end up getting squashed together.
p.StartInfo.Arguments = srcDir.FullName + " " + dstDir.FullName;
But of course, if either srcDir.FullName or dstDir.FullName contain space characters of their own (and FullName suggests they do), you will need to surround them with double quote characters.
p.StartInfo.Arguments = "\"" srcDir.FullName + "\" \"" + dstDir.FullName + "\"";
I'm trying to unzip a file from a winform application.
I'm using this code :
string dezarhiverPath = #AppDomain.CurrentDomain.BaseDirectory + "\\7z.exe";
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = dezarhiverPath;
pro.Arguments = #" e c:\TEST.ZIP";
Process x = Process.Start(pro);
x.WaitForExit();
The code doesn't return error but doesn't anything.
I tried this command also from cmd :
K:\>"C:\Test\7z.exe" e "c:\TEST.ZIP"
but in cmd ,I receive this error message :
7-Zip cannot find the code that works with archives.
Can somebody help me to unzip some files from c# ?
Thanks!
Why would you bother trying to use the 7z.exe application externally? That is a very kludgy way of doing it. Instead use one of the many libraries at your disposal.
If this is a new application, and you are targeting .NET 4.5, The new System.IO.Compression namespace has a ZipFile class.
Alternatively, SharpZipLib is a GPL library for file compression in .NET. There are online samples.
Also available is DotNetZip which is Ms-PL licensed.
Hey use this code below , you must have 7zip application in your system .
public void ExtractFile(string source, string destination)
{
string zPath = #"C:\Program Files\7-Zip\7zG.exe";// change the path and give yours
try
{
ProcessStartInfo pro = new ProcessStartInfo();
pro.WindowStyle = ProcessWindowStyle.Hidden;
pro.FileName = zPath;
pro.Arguments = "x \"" + source + "\" -o" + destination;
Process x = Process.Start(pro);
x.WaitForExit();
}
catch (System.Exception Ex) {
//DO logic here
}
}
to create :
public void CreateZip()
{
string sourceName = #"d:\a\example.txt";
string targetName = #"d:\a\123.zip";
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = #"C:\Program Files\7-Zip\7zG.exe";
p.Arguments = "a -tgzip \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
p.WindowStyle = ProcessWindowStyle.Hidden;
Process x = Process.Start(p);
x.WaitForExit();
}
Refer Following Code:
using System.IO.Compression;
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.zip";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
Referance Link:
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/849c4969-24b1-4650-88a5-5169727e527f/
You can use SevenZipSharp library
using (var input = File.OpenRead(lstFiles[0]))
{
using (var ds = new SevenZipExtractor(input))
{
//ds.ExtractionFinished += DsOnExtractionFinished;
var mem = new MemoryStream();
ds.ExtractFile(0, mem);
using (var sr = new StreamReader(mem))
{
var iCount = 0;
String line;
mem.Position = 0;
while ((line = sr.ReadLine()) != null && iCount < 100)
{
iCount++;
LstOutput.Items.Add(line);
}
}
}
}
Try this
string fileZip = #"c:\example\result.zip";
string fileZipPathExtactx= #"c:\example\";
ProcessStartInfo p = new ProcessStartInfo();
p.WindowStyle = ProcessWindowStyle.Hidden;
p.FileName = dezarhiverPath ;
p.Arguments = "x \"" + fileZip + "\" -o" + fileZipPathExtact;
Process x = Process.Start(p);
x.WaitForExit();
This maybe can help you.
//You must create an empty folder to remove.
string tempDirectoryPath = #"C:\Users\HOPE\Desktop\Test Folder\zipfolder";
string zipFilePath = #"C:\Users\HOPE\Desktop\7za920.zip";
Directory.CreateDirectory(tempDirectoryPath);
ZipFile.ExtractToDirectory(zipFilePath, tempDirectoryPath);
I have requirement to execute the command line arguments. If file path contains the Spaces it doesn’t work properly. It returns the error file not found. The program is given below.
public void Method()
{
string docFile = #"C:\Test Document1.doc";
string docxFile = #"C:\Test Document1.docx";
string file = #"C:\doc2x_r649 (1)\doc2x_r649\doc2x.exe";
ExecuteCommand(file, string.Format(docFile + " -o " + docxFile));
}
public static string ExecuteCommand(string file, string command)
{
String result;
try
{
//Create a new ProcessStartInfo
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo();
//Settings
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.FileName = file;
procStartInfo.Arguments = command;
//Create new Process
System.Diagnostics.Process proc = new System.Diagnostics.Process();
//Set ProcessStartInfo
proc.StartInfo = procStartInfo;
//Start Process
proc.Start();
//Wait to exit
proc.WaitForExit();
//Get Result
result = proc.StandardOutput.ReadToEnd();
//Return
return result;
}
catch
{
}
return null;
}
If file path doesn't contains spaces it works properly.
Have you tried adding quotes to your paths?
ExecuteCommand(file, string.Format("\"" + docFile + "\" -o \"" + docxFile + "\""));
Try this
ExecuteCommand(file, string.Format("\"{0}\" -o \"{1}\"",docFile , docxFile));
I am developing a software that will list all the software install
in Computer
now i want to Uninstall it using my Program In C# by
calling the Uninstall Key of that software in
Registry Key
My Program Is
Like That But the Process Is Not Working
var UninstallDir = "MsiExec.exe /I{F98C2FAC-6DFB-43AB-8B99-8F6907589021}";
string _path = "";
string _args = "";
Process _Process = new Process();
if (UninstallDir != null && UninstallDir != "")
{
if (UninstallDir.StartsWith("rundll32.exe"))
{
_args = ConstructPath(UninstallDir);
_Process.StartInfo.FileName = Environment.SystemDirectory.ToString() + "\\explorer.exe";
_Process.StartInfo.Arguments = Environment.SystemDirectory.ToString() + "\\" + UninstallDir;
_Process.Start();
}
else if (UninstallDir.StartsWith("MsiExec.exe"))
{
_args = ConstructPath(UninstallDir);
_Process.StartInfo.FileName = Environment.SystemDirectory.ToString() + "\\cmd.exe";
_Process.StartInfo.Arguments = Environment.SystemDirectory.ToString() + "\\" + UninstallDir;
_Process.Start();
}
else
{
//string Path = ConstructPath(UninstallDir);
_path = ConstructPath(UninstallDir);
if (_path.Length > 0)
{
_Process.StartInfo.FileName = _path;
_Process.StartInfo.UseShellExecute = false;
_Process.Start();
}
}
Try this approach:
Process p = new Process();
p.StartInfo.FileName = "msiexec.exe";
p.StartInfo.Arguments = "/x {F98C2FAC-6DFB-43AB-8B99-8F6907589021}/qn";
p.Start();
Refer to this link: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/msiexec.mspx?mfr=true
HTH.
The problem with your misexec.exe code is that running cmd.exe someprogram.exe doesn't start the program because cmd.exe doesn't execute arguments passed to it. But, you can tell it to by using the /C switch as seen here. In your case this should work:
_Process.StartInfo.FileName = Environment.SystemDirectory.ToString() + "\\cmd.exe";
_Process.StartInfo.Arguments = "/C " + Environment.SystemDirectory.ToString() + "\\" + UninstallDir;
Where all I did was add /C (with a space after) to the beginning of the arguments. I don't know how to get your rundll32.exe code to work, however.
Your solution looks good, but keep a space before \qn:
p.StartInfo.Arguments = "/x {F98C2FAC-6DFB-43AB-8B99-8F6907589021} /qn";
Otherwise it wont work in silent mode.