我尝试为自己做一些最小化的应用程序,但选择的路径有点问题。我有以下代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void FilesCountNumberShow_button_Click(object sender, RoutedEventArgs e)
{
// Try to count nu,ber of files in folder
int fCount = Directory.GetFiles(count_path, "*", SearchOption.TopDirectoryOnly).Length;
FilesCountNumber_Label.Content = "Files in folder: " + fCount;
}
private void SelectFolderPath_button_Click(object sender, RoutedEventArgs e)
{
// These code is for open File Dialog and choose older path as count_path
var SelectFolderPath_Dialog = new WinForms.FolderBrowserDialog();
if (SelectFolderPath_Dialog.ShowDialog() == WinForms.DialogResult.OK)
{
string count_path = SelectFolderPath_Dialog.SelectedPath;
MessageBox.Show(count_path);
}
}
}
}
如何在
中引用变量count_path
int fCount = Directory.GetFiles(count_path, "*", SearchOption.TopDirectoryOnly).Length;
我掌握了不存在的信息(我认为SelectFolderPath_button_Click
中的locla变量对吗?如何设置全局变量?
我这样做。我在此处添加string count_path { get; set; }
:
public partial class MainWindow : Window
{
string count_path { get; set; }
public MainWindow()
{
InitializeComponent();
}
并修改
private void SelectFolderPath_button_Click(object sender, RoutedEventArgs e)
{
var SelectFolderPath_Dialog = new WinForms.FolderBrowserDialog();
if (SelectFolderPath_Dialog.ShowDialog() == WinForms.DialogResult.OK)
{
count_path = SelectFolderPath_Dialog.SelectedPath;
MessageBox.Show(count_path);
}
}
这是一个好的解决方案,还是应该以其他方式解决?
答案 0 :(得分:0)
将所选路径存储在私有字段中,并验证是否已设置它:
public partial class MainWindow : Window
{
private string count_path;
public MainWindow()
{
InitializeComponent();
}
private void FilesCountNumberShow_button_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(count_path))
{
MessageBox.Show("You must select a folder first!");
}
else
{
// Try to count nu,ber of files in folder
int fCount = Directory.GetFiles(count_path, "*", SearchOption.TopDirectoryOnly).Length;
FilesCountNumber_Label.Content = "Files in folder: " + fCount;
}
}
private void SelectFolderPath_button_Click(object sender, RoutedEventArgs e)
{
// These code is for open File Dialog and choose older path as count_path
var SelectFolderPath_Dialog = new WinForms.FolderBrowserDialog();
if (SelectFolderPath_Dialog.ShowDialog() == WinForms.DialogResult.OK)
{
count_path = SelectFolderPath_Dialog.SelectedPath;
MessageBox.Show(count_path);
}
}
}
答案 1 :(得分:-1)
//add assembly reference System.Windows.Forms
private void SelectFolderPath_button_Click(object sender, RoutedEventArgs e)
{
using (var SelectFolderPath_Dialog = new System.Windows.Forms.FolderBrowserDialog())
{
if (SelectFolderPath_Dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string count_path = SelectFolderPath_Dialog.SelectedPath;
MessageBox.Show(count_path);
}
}
}