user3569641
user3569641

Reputation: 922

how to limit number of uploads in multi-select OpenFileDialog in C#

How can I limit the number of files to be uploaded using the multi-select openfiledialog in c#?

Here's my code:

private void btn_upload_Click(object sender, EventArgs e)
{
    OpenFileDialog op1 = new OpenFileDialog();
    op1.Multiselect = true;
    op1.ShowDialog();
    op1.Filter = "allfiles|*.xls";
    textBox1.Text = op1.FileName;
    int count = 0;
    string[] FName;
    foreach (string s in op1.FileNames)
    {
        FName = s.Split('\\');
        File.Copy(s, "C:\\file\\" + FName[FName.Length - 1]);
        count++;
    }
    MessageBox.Show(Convert.ToString(count) + " File(s) copied");
 }

It will upload as how much the user wants to. But I want to limit it by 5 files only.

Upvotes: 5

Views: 2274

Answers (2)

001
001

Reputation: 13533

I just tested and this works:

private void btn_upload_Click(object sender, EventArgs e)
{
    OpenFileDialog op1 = new OpenFileDialog();
    op1.Multiselect = true;
    op1.FileOk += openFileDialog1_FileOk;   // Event handler
    op1.ShowDialog();

    // etc
 }

void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
    OpenFileDialog dlg = sender as OpenFileDialog;
    if (5 < dlg.FileNames.Length)
    {
        MessageBox.Show("Too Many Files");
        e.Cancel = true;
    }
}

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

You can't do that directly but you can check the selected files count and display a message to user:

if(op1.FileNames.Length > 5)
{
     MessageBox.Show("your message");
     return;
}

Or you can take the first five file from selected files:

foreach (string s in op1.FileNames.Take(5))
{
    ...
}

Upvotes: 5

Related Questions