gpt4 book ai didi

C# OpenFiledialog 多选字符串数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:01:28 24 4
gpt4 key购买 nike

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

代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com