3

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.

Error when calling convert.exe

Side note: I wouldn't want to use GhostScript just yet because I feel like I am really close to an answer using ImageMagick.

LampPost
  • 856
  • 11
  • 30
  • 1
    What have you checked so far? Did you step over your code and verify the proper variable content? – Tobias Knauss Aug 23 '15 at 15:28
  • What is the exit code? Any errors from that exe you run? If you hookup the events for the data received events as shown in [my answer here](http://stackoverflow.com/a/15032982/578411) you can capture what was in the output. – rene Aug 23 '15 at 15:37
  • What is the error you are seeing? Have you got Ghostscript on your PATH for the C# program as your PATH there may differ from your PATH at the command line. – Mark Setchell Aug 23 '15 at 17:27
  • @TobiasKnauss what i have checked so far is the variable arguments that I am passing in. My `string arguments` variable is the following `"\"C:\\Users\\rwong\\Desktop\\RoundPoint\\1000965275\\1000965275_157_Credit File_10.PDF\" \"C:\\Users\\rwong\\Desktop\\RoundPoint\\1000965275\\1000965275_157_Credit File_10.png\""` – LampPost Aug 24 '15 at 14:26
  • Try starting the process without arguments to see whether it is running at all. Also, use shorter paths and filenames for your test, without spaces, like c:\temp\file.pdf. – Tobias Knauss Aug 24 '15 at 14:37
  • @rene I have updated the post if it helps answer your questions. – LampPost Aug 24 '15 at 15:48
  • If you run the same command from the commandline you don't receive those errors? – rene Aug 24 '15 at 16:22
  • Nope I do not receive any errors. I tried with with spaces in the file name and it was also successful. @MarkSetchell to my knowledge I am not running GhostScript unless ImageMagick calls it without my knowledge. – LampPost Aug 24 '15 at 17:08

2 Answers2

1

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.

LampPost
  • 856
  • 11
  • 30
0

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);
    }
}
Mohit S
  • 13,723
  • 6
  • 34
  • 69
  • Thanks for your output for both questions! I received and error when trying to call `DataReceivedEventHandler` something about “an object reference is required for the non-static field, method or property" so I added the keyword static in front of the function declaration and it complied the function never ran. – LampPost Aug 24 '15 at 14:01
  • Where did u added the static keyword. You have an Error handler as well in the Process. Please have a look that you should not be running the program in the Console app. Make a WPF or WinForm App. – Mohit S Aug 25 '15 at 01:52