Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process multiple selected files from OpenFileDialog

I used foreach loop for reading multiple image files but I am able to only stream first selected file.When I try to save multiple different images, outputs are like exact copies of the first selected image instead of remaining different images.

    private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(DBHandler.GetConnectionString());
        try
        {
            OpenFileDialog fop = new OpenFileDialog();
            fop.Multiselect = true;

            fop.InitialDirectory = "C:\\";
            fop.Filter = "JPG,JPEG|*.jpg|PNG|*png";
            if (fop.ShowDialog() == DialogResult.OK)
            {

                foreach (String files in fop.FileNames)
                {
                    FileStream FS = new FileStream(@fop.FileName, FileMode.Open, FileAccess.Read);
                    byte[] img = new byte[FS.Length];
                    FS.Read(img, 0, Convert.ToInt32(FS.Length));

                    if (con.State == ConnectionState.Closed)
                        con.Open();
                    SqlCommand cmd = new SqlCommand("SaveImage", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@img", SqlDbType.Image).Value = img;
                    cmd.ExecuteNonQuery();

                }

                MessageBox.Show("Image has been saved successfully!!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

I want to see all images on the same form.

My expectation: A-B-C-D (each letter represents different retrieved images. "A" is the first selected file from dialog box)

Actual output: A-A-A-A. Why does that happen?

like image 780
SophisticatedUndoing Avatar asked Nov 28 '25 23:11

SophisticatedUndoing


1 Answers

In your loop, you're using fop.FileName, which returns the first selected file:

This property can only be the name of one selected file. If you want to return an array containing the names of all selected files in a multiple-selection dialog box, use FileNames.

foreach (String files in fop.FileNames)
{
    FileStream FS = new FileStream(@fop.FileName, FileMode.Open, FileAccess.Read);

    // ...
}

Change it instead to use the iteration variable filename:

foreach (String filename in fop.FileNames)
{
    FileStream FS = new FileStream(filename, FileMode.Open, FileAccess.Read);

    // ...
}

Related: OpenFileDialog reads only the first file.

like image 156
CodeCaster Avatar answered Dec 01 '25 11:12

CodeCaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!