C# Save Image files using SaveFileDialog or FolderBrowserDialog

409 views Asked by At

I'm trying to save image files which are converted from PDF to PNG. I want my application to save the converted image if the PDF was a single page document using the "SaveFileDialog", and if the PDF file was a multi-page document, I then want my application to save them into a folder using the "FolderBrowserDialog".

My problem is that if the PDF file was a multi-page document, my code would first save the first image (after conversion) using the "SaveFileDialog" before attempting to save the rest of the images using "FolderBrowserDialog".

Here is what I've tried.

Image = imageToConvert = null;

for (int i = 0; i < images.Length; i++)
{
    if (i == 0)
    {
        //Save converted image if PDF is single page
         imageToConvert = images[i];

        SaveFileDialog _saveFile = new SaveFileDialog();
        _saveFile.Title = "Save file";
        _saveFile.Filter = "PNG|*.png";
        _saveFile.FileName = Lbl_OriginalFileName.Text;


        if (_saveFile.ShowDialog() == DialogResult.OK)
        {
            imageToConvert.Save(_saveFile.FileName, ImageFormat.Png);

            imageToConvert.Dispose();
        }
        else if (_saveFile.ShowDialog() == DialogResult.Cancel)
        {
            return;
        }
    }
    else
    {
        if (i > 0)
        {
            // Save converted Images if PDF is multi-page
            Image imageToConvert2 = images[i];

            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowDialog();
            fbd.Description = "Select the folder you want save your files into.";

            string pathString = Path.Combine(fbd.SelectedPath, subFolder);
            Directory.CreateDirectory(pathString);

            if (fbd.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            
                string saveFileNamesPNG = string.Format(Lbl_OriginalFileName.Text + "_" + i.ToString() + ".png", ImageFormat.Png);
                imageToConvert.Save(Path.Combine(pathString, saveFileNamesPNG));
           
            imageToConvert.Dispose();
        }
    }
}

I would really appreciate any help.

1

There are 1 answers

0
Opu On

I moved the test outside the loop and then checked if it is one page and use the SaveFileDialog. And if there are more than one, I then used a FolderBrowserDialog with the For-loop to save the images.