C# 如何获取变量";“安全文件名”;从另一种方法?
如何从另一个方法获取变量“SafeFileName”? 在按钮1中,我有OpenFileDialog,在按钮2中,我想获得所有文件名 我使用循环:C# 如何获取变量";“安全文件名”;从另一种方法?,c#,winforms,C#,Winforms,如何从另一个方法获取变量“SafeFileName”? 在按钮1中,我有OpenFileDialog,在按钮2中,我想获得所有文件名 我使用循环: foreach (string fileName in openFileDialog1.SafeFileNames) 在公开课上,我有: public string[]fileName{get;private set;} 但它不起作用。我可以创建新的数组并填充第一个方法,但我正在寻找另一个更好的解决方案 代码: 我有这样的想法: public pa
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
为空。如果从第一个方法调用第二个方法,可以将字符串数组传递给第二个方法。否则,可以在类中使用私有字段引用数组并在第二个方法中使用
编辑:您可以按如下方式编辑代码:
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循环中的迭代变量有一些混淆。该变量仅存在于循环中,并且在每次迭代时为其分配一个新值。是否要在同一文件夹中获取文件名?为什么不使用OpenFolderDialog?
openFileDialog1.Multiselect=true代码>特定文件而不是整个folderI编辑了我的答案。它现在回答你的问题了吗?此外,请删除您的答案并将其添加到问题中,因为它是问题的一部分。