如何从另一种方法获取变量“SafeFileNames”? 在按钮1中我有OpenFileDialog,在按钮2中我想获取所有文件名。
我使用循环:
foreach (string fileName in openFileDialog1.SafeFileNames)
在公共部门类表格中我有:
public string[] fileName { get; private set; }
但它不起作用。我可以创建新的数组并填写第一种方法,但我正在寻找另一种更好的解决方案。
我有这样的事情:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string[] fileName { get; private set; }
int numberOfFiles { get; set; }
public void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "txt";
openFileDialog1.Filter = "Text files (*.txt)|*.txt";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = false;
openFileDialog1.Multiselect = true;
textBox1.Text = "";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
int number = 0;
foreach (string fileName in openFileDialog1.SafeFileNames)
{
}
}
}
public void button2_Click(object sender, EventArgs e)
{
HERE - I want to know string from openFileDialog1.SafeFileNames
}
现在string[] fileName
为空。
答案 0 :(得分:1)
如果从第一个方法调用第二个方法,则可以将字符串数组传递给第二个方法。否则,您可以使用类中的私有字段来引用数组并在第二种方法中使用。
修改:您可以按如下方式修改代码:
public Form1()
{
InitializeComponent();
}
public string[] fileNames { get; private set; }
int numberOfFiles { get; set; }
public void button1_Click(object sender, EventArgs e)
{
//Your openFileDialog1 initialisation and other stuff here
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileNames = openFileDialog1.SafeFileNames;
numberOfFiles = fileName.Length;
}
}
public void button2_Click(object sender, EventArgs e)
{
foreach (string fileName in fileNames)
{
//You can access the name of each file using fileName now
}
}
我认为你对foreach循环中的迭代变量有一些困惑。该变量仅存在于循环内部,并在每次迭代时为其分配一个新值。