C# OpenFiledialog 多选字符串数组

标签 c# dialog

我想存储在我的字符串数组中选择的文件名。

代码:

if (openFileDialog.ShowDialog() == DialogResult.OK)
       string filename ;
       string[] result = null;
       int i = 0;
      try                {
                if ((myStream = openFileDialog.OpenFile()) != null)
                {
                    foreach (String file in openFileDialog.FileNames)
                    {
                        filename = Path.GetFileName(file);
                        result[i] = filename;
                        MessageBox.Show(result[i]); // only show the name of file
                        i = i + 1;

                    }                  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk.   Original error: " + ex.Message);
            }

错误代码是:“索引超出数组大小”

我该如何解决?

最佳答案

如果您事先知道要添加多少项,则只应使用数组。你应该使用一个列表,这样你就可以随时向它添加额外的东西。因为您从未定义数组的大小,所以我相信您会得到错误。

如果您要动态添加内容,您或许应该使用列表。

List<string> result = new List<string>();

添加时

result.add(filename);

显示

MessageBox.Show(result[i])

所以你的代码会是

if (openFileDialog.ShowDialog() == DialogResult.OK)
   string filename ;
   List<string> result = new List<string>();
   int i = 0;
  try                {
            if ((myStream = openFileDialog.OpenFile()) != null)
            {
                foreach (String file in openFileDialog.FileNames)
                {
                    filename = Path.GetFileName(file);
                    result.add(filename);
                    MessageBox.Show(result[i]); // only show the name of file
                    i = i + 1;

                }                  
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: Could not read file from disk.   Original error: " + ex.Message);
        }

关于C# OpenFiledialog 多选字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42930228/

相关文章:

c# - 如何判断 linq to sql 对象是新的、修改的还是未更改的?

c# - 云存储账户

c# - Linq:前瞻性条件

c++ - 将 somedialog.h 包含到项目的其他部分会使 ui_somedialog.h 对编译器不可见

android - AlertDialog 或自定义对话框

android - 使用 Sqlite Cursor 时如何让对话框中的 setMultiChoiceItems 复选框更新

c# - 在控制台应用程序中托管的 WCF 服务

android - Android 上的对话框是异步的吗?

c# - 如何将数据传递给 wpf mvvm 对话框?

c# - 在 C# 中实现一个使用并返回相同接口(interface)的接口(interface)