问题描述
亲爱的朋友,
首先,我要感谢大家花时间阅读并友好回答我的问题.建议我在定义时设置数组大小".
我理解它,但事实是,在定义时,我不知道它可能需要的大小.如前所述,我必须定义文件名"
这是button1_Click事件外部的字符串数组(由于某些原因).但是在这种情况下,它的大小将变得清晰.所以我不知道.
换句话说,当我需要在定义时定义一个大小未知的数组以免引发此类错误时该怎么办?
在下面,为方便起见,我重复了我的问题
*************
你好,
在程序中,用户可以选择一些文件进行某些操作.在"OpenFileDialog"中,可以返回文件的完整路径,目录路径和文件名.我需要的是将文件路径与其后面的文件名分开.为此,我需要将值一一设置为字符串数组.我使用了下面的代码,但有如下错误:
空引用异常未处理
对象引用未设置为对象的实例.
你能帮我吗?
非常感谢
Dear Friends,
I should First thank you all for taking time reading and kindly answering my question. It was suggested that I should set the Array Size at the time of definition.
I understand it but the fact is, at the time of definition, I am not aware of its probable size needed. As it was pointed I have to define the ‘FileNames’
which is an Array of string outside of button1_Click event (due to some reasons). But within this event the size of it will become clear. So I don’t know it in advance.
In other words, what should I do when I need to define an array with unknown size at the time of definition so that it won’t raise such error?
In bellow my question is repeated for convenience
*************
Hello,
In a program the user may choose some files to have some operation on. In ‘OpenFileDialog’, Full path of files, both path of directory and File names could be returned. What I require is to separate File path from its following File name. To do so, I needed to set value to Array of string one by one. I used the code below but there is a error as follows:
Null Reference Exception was unhandled
Object reference not set to an instance of an object.
Could you please help me?
Thanks a lot
public Form1()
{
InitializeComponent();
}
string[] FilePathNames;
string[] FileNames; // I need to define here, instead of defining inside ''button1_Click'' method
private void button1_Click(object sender, EventArgs e)
{
...
if (myOpenFileDialog.ShowDialog() == DialogResult.OK)
{
FilePathNames = myOpenFileDialog.FileNames;
//FilePathNames, includes Full path of files, both path of directory and File names
int counter = 0;
// in loop below, i want to detach File path from its following File name
foreach (string fname in FilePathNames)
{
int idx = fname.LastIndexOf(''\\'');
FileNames[counter] = fname.Substring(idx + 1); // Here, Error Ocuurs!!!
counter += 1;
}
}
}
推荐答案
List<string> fileList = new List<string>();
// in loop below, i want to detach File path from its following File name
foreach (string fname in FilePathNames)
{
int idx = fname.LastIndexOf(''\\'');
fileList.Add(fname.Substring(idx+1));
}
</string></string>
string[] tempFileNames = new string[myOpenFileDialog.FileNames.Length];
并复制到ur变量(可以进行浅拷贝,深拷贝)
and copy to ur variable ( you can shallowcopy,deep copy)
FileNames = tempFileNames; // just template
string[] FileNames=new string[300];
希望有帮助
hope this help
这篇关于将值一一设置为字符串数组时,出现“空引用异常"(2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!