Search code examples
c#winformspictureboxopenfiledialog

How can I save Image files in in my project folder?


In my Windows application, I have a PictureBox and a Button control. I want to load an Image file from user from the button's OnClick event and save that image file in a folder name "proImg" which is in my project. Then I want to show that image in the PictureBox.

I have written this code, but it is not working:

OpenFileDialog opFile = new OpenFileDialog();
opFile.Title = "Select a Image";
opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
if (opFile.ShowDialog() == DialogResult.OK)
{
    try
    {
        string iName = opFile.FileName;
        string filepath = "~/images/" + opFile.FileName;
        File.Copy(iName,Path.Combine("~\\ProImages\\", Path.GetFileName(iName)));
        picProduct.Image = new Bitmap(opFile.OpenFile());
    }
    catch (Exception exp)
    {
        MessageBox.Show("Unable to open file " + exp.Message);
    }
}
else
{
    opFile.Dispose();
}

It's not able to save the image in the "proImg" folder.

enter image description here


Solution

  • Actually the string iName = opFile.FileName; is not giving you the full path. You must use the SafeFileName instead. I assumed that you want your folder on your exe directory also. Please refer to my modifications:

    OpenFileDialog opFile = new OpenFileDialog();
    opFile.Title = "Select a Image";
    opFile.Filter = "jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
    
    string appPath = Path.GetDirectoryName(Application.ExecutablePath) + @"\ProImages\"; // <---
    if (Directory.Exists(appPath) == false)                                              // <---
    {                                                                                    // <---
        Directory.CreateDirectory(appPath);                                              // <---
    }                                                                                    // <---
    
    if (opFile.ShowDialog() == DialogResult.OK)
    {
        try
        {
            string iName = opFile.SafeFileName;   // <---
            string filepath = opFile.FileName;    // <---
            File.Copy(filepath, appPath + iName); // <---
            picProduct.Image = new Bitmap(opFile.OpenFile());
        }
        catch (Exception exp)
        {
            MessageBox.Show("Unable to open file " + exp.Message);
        }
    }
    else
    {
        opFile.Dispose();
    }