如何从另一个函数访问文件
How to access file from another function
我目前正在开发如下所示的 C# WPF 应用程序。我想要做的是,按下第一个按钮时,基本上会打开一个浏览对话框,您可以在其中 select 多个文件。我也想访问其他按钮内的那些路径。最终我希望能够单击浏览按钮,select 一个文件,然后按第二个按钮在路径上执行一个功能。任何帮助将不胜感激!
private void Button_Click1(object sender, RoutedEventArgs e) //BROWSE BUTTON
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Multiselect = true;
dlg.FileName = "Document";
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
foreach (String file in dlg.FileNames)
{
// do something
}
}
private void Button_Click(object sender, RoutedEventArgs e, string p)
{
myFunction(p);
}
您可以在 Button_Click1
方法之外简单地拥有一个私有变量,它将保存所选的文件名。
string[] files;
private void Button_Click1(object sender, RoutedEventArgs e) //BROWSE BUTTON
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Multiselect = true;
dlg.FileName = "Document";
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
files = dlg.FileNames;
else
{
//Do something useful if the user cancels the dialog
}
}
然后在您的其他方法中,只需引用 files
变量,该变量将保存您选择的文件名数组。
用法示例:
for (int i = 0; i < files.Length; i++)
{
myFunction(files[i]);
}
以上代码将遍历数组中的每个文件并调用myFunction
方法。
我目前正在开发如下所示的 C# WPF 应用程序。我想要做的是,按下第一个按钮时,基本上会打开一个浏览对话框,您可以在其中 select 多个文件。我也想访问其他按钮内的那些路径。最终我希望能够单击浏览按钮,select 一个文件,然后按第二个按钮在路径上执行一个功能。任何帮助将不胜感激!
private void Button_Click1(object sender, RoutedEventArgs e) //BROWSE BUTTON
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Multiselect = true;
dlg.FileName = "Document";
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
foreach (String file in dlg.FileNames)
{
// do something
}
}
private void Button_Click(object sender, RoutedEventArgs e, string p)
{
myFunction(p);
}
您可以在 Button_Click1
方法之外简单地拥有一个私有变量,它将保存所选的文件名。
string[] files;
private void Button_Click1(object sender, RoutedEventArgs e) //BROWSE BUTTON
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Multiselect = true;
dlg.FileName = "Document";
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
files = dlg.FileNames;
else
{
//Do something useful if the user cancels the dialog
}
}
然后在您的其他方法中,只需引用 files
变量,该变量将保存您选择的文件名数组。
用法示例:
for (int i = 0; i < files.Length; i++)
{
myFunction(files[i]);
}
以上代码将遍历数组中的每个文件并调用myFunction
方法。