c# - 打开多个文件(OpenFileDialog,C#)

标签 c# winforms file openfiledialog

我尝试使用 OpenFileDialog 一次打开多个文件,使用 FileNames 而不是 FileName。但是我在任何地方都看不到有关如何完成此操作的示例,甚至在 MSDN 上也看不到。据我所知 - 也没有关于它的文档。以前有人这样做过吗?

最佳答案

您必须设置 OpenFileDialog.Multiselect属性值为 true,然后访问 OpenFileDialog.FileNames 属性。

检查这个样本

private void Form1_Load(object sender, EventArgs e)
{
    InitializeOpenFileDialog();
}

private void InitializeOpenFileDialog()
{
    // Set the file dialog to filter for graphics files.
    this.openFileDialog1.Filter =
        "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
        "All files (*.*)|*.*";

    //  Allow the user to select multiple images.
    this.openFileDialog1.Multiselect = true;
    //                   ^  ^  ^  ^  ^  ^  ^

    this.openFileDialog1.Title = "My Image Browser";
}

private void selectFilesButton_Click(object sender, EventArgs e)
{
    DialogResult dr = this.openFileDialog1.ShowDialog();
    if (dr == System.Windows.Forms.DialogResult.OK)
    {
        // Read the files
        foreach (String file in openFileDialog1.FileNames) 
        {
            // Create a PictureBox.
            try
            {
                PictureBox pb = new PictureBox();
                Image loadedImage = Image.FromFile(file);
                pb.Height = loadedImage.Height;
                pb.Width = loadedImage.Width;
                pb.Image = loadedImage;
                flowLayoutPanel1.Controls.Add(pb);
            }
            catch (SecurityException ex)
            {
                // The user lacks appropriate permissions to read files, discover paths, etc.
                MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
                    "Error message: " + ex.Message + "\n\n" +
                    "Details (send to Support):\n\n" + ex.StackTrace
                );
            }
            catch (Exception ex)
            {
                // Could not load the image - probably related to Windows file system permissions.
                MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                    + ". You may not have permission to read the file, or " +
                    "it may be corrupt.\n\nReported error: " + ex.Message);
            }
        }
    }

关于c# - 打开多个文件(OpenFileDialog,C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1311578/

相关文章:

c# 将IE浏览器的内容保存为html

c# - Visual Studio 2010 设计器生成无效代码

css - Magento 隐藏的 CSS 文件

c# - 30 分钟后 Azure 函数超时

c# - ef core fluent api 设置接口(interface)的所有列类型

c# - 在 c# (winForms) 中用字符串列表制作树结构

c# - 当 Windows 从 sleep 模式唤醒时启动应用程序

c++ - 哪种方法最适合从光驱中快速读取文件?

java - 搜索列表中与 id 有关的最后一个值

c# - 如果使用 `using` 语句,什么时候需要调用 IDisposable?