为什么在使用openFileDialog时我没有看到我改变的所有设置?

时间:2016-01-19 16:56:29

标签: c# .net winforms

在form1的顶部,我做了

OpenFiledialog openFileDialog1 = new OpenFiledialog();

然后:

private void changeWorkingDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
    DialogResult result = openFileDialog1.ShowDialog();
    openFileDialog1.Filter =  
"BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
   + "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
    openFileDialog1.InitialDirectory = @"c:\";
    openFileDialog1.Multiselect = true;
    if (result == DialogResult.OK)
    {
        string[] files = openFileDialog1.FileNames;

        try
        {
            if (files.Length > 0)
            {
                label6.Text = files.Length.ToString();
                label6.Visible = true;
                string directoryPath = Path.GetDirectoryName(files[0]);
                label12.Text = directoryPath;
                label12.Visible = true;
            }
        }
        catch (IOException)
        {
        }
    }
}

但是当我点击按钮时,init目录是文件而不是c:我根本看不到过滤器,但我看到所有文件。这就像我没有影响的设置。

3 个答案:

答案 0 :(得分:5)

ShowDialog是模态的,因此它等待用户单击“确定/取消”。

只有这样,其余代码才会运行。 完成属性设置后,您应该只调用ShowDialog

openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg...";
openFileDialog1.InitialDirectory = @"c:\";
openFileDialog1.Multiselect = true;

DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)

答案 1 :(得分:4)

你的逻辑错误。您在配置设置之前显示对话框

// Configure it first
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
   + "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
openFileDialog1.InitialDirectory = @"c:\";
openFileDialog1.Multiselect = true;

// Then show it and wait for the user to make a selection or cancel
DialogResult result = openFileDialog1.ShowDialog();

// Take some action if the user made a selection
if (result == DialogResult.OK)
{
    ...

作为旁注,请注意吃异常。至少,记录错误并通知用户。

catch (IOException ex)
{
    // log ex.ToString() somewhere

    MessageBox.Show("An error has occurred!\r\n\r\n" + ex.Message);
}

答案 2 :(得分:1)

问题是您在设置属性之前调用ShowDialog(),这应该适合您:

    openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
       + "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";

    openFileDialog1.InitialDirectory = @"c:\";
    openFileDialog1.Multiselect = true;

    DialogResult result = openFileDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        string[] files = openFileDialog1.FileNames;

        try
        {
        if (files.Length > 0)
            {
                label6.Text = files.Length.ToString();
                label6.Visible = true;
                string directoryPath = Path.GetDirectoryName(files[0]);
                label12.Text = directoryPath;
                label12.Visible = true;
            }
        }
        catch (IOException)
        {
        }
   }