在方法之外拉变量声明:
string[] filePaths; if (chkIncludeSubFolders.Checked) { filePaths = Directory.GetFiles(txtPath.Text, txtFormat.Text, SearchOption.AllDirectories); } else { filePaths = Directory.GetFiles(txtPath.Text, txtFormat.Text, SearchOption.TopDirectoryOnly); } // You can use filePaths here
你可以按照其他答案的建议,filePaths
在if/else之外声明.但是,你重复自己,因为两个调用之间唯一不同的是选项.所以先设置它们然后拨打电话:
var searchOptions = chkIncludeSubFolders.Checked ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; string[] filePaths = Directory.GetFiles(txtPath.Text, txtFormat.Text, searchOptions); foreach (string item in filePaths) { //my code }