【发布时间】:2015-04-26 16:35:20
【问题描述】:
好的,所以请不要太激怒我,这是我在这里的第一个问题,也许我想要做的甚至是不可能的。显然我不是专家;这就是我来找你的原因。 :)
我已经搜索了整个这里、MSDN 和互联网的其余部分(大部分都指向这里),但没有任何运气。我确实看到了一个问题,询问有关使用OpenFileDialog 选择文件夹而不是文件的问题。我几乎可以肯定我已经在主流应用程序中看到了这一点,但是这个问题被标记为过于模糊,并且在回复中没有解决这个特别的警告。
我有一些需要文件/文件夹路径的文本框。我想将处理此问题的两种方法简化为一种。唯一不同的是,一次选择文件,另一次选择文件夹。为了简单和可读性,我想合并它们。
这是否可能,而不是将每个代码方法的内容逐字放入一个大的IF 中?
这里有两种方法:
private void FolderBrowser(object sender, EventArgs e)
{
TextBox SenderBox = sender as TextBox;
if (SenderBox.Text != "")//if the text box is not empty
{
//set the selected path to the text box's current contents (incase of accidental entry)
FileBrowserDialog.FileName = SenderBox.Text;
}
if (FileBrowserDialog.ShowDialog() == DialogResult.OK)
{
SenderBox.Text = FileBrowserDialog.FileName;
}
}
private void FileBrowser(object sender, EventArgs e)
{ //basically the same as the folder browser above, but for selecting specific files
TextBox SenderBox = sender as TextBox;
if (SenderBox.Text != "")//if the text box is not empty
{
//set the selected path to the text box's current contents (incase of accidental entry)
FileBrowserDialog.FileName = SenderBox.Text;
}
if (FileBrowserDialog.ShowDialog() == DialogResult.OK)
{
SenderBox.Text = FileBrowserDialog.FileName;
}
}
我为每个TextBox 添加了一个Tag,表示它需要文件还是文件夹。我想使用Tag 作为我确定是否应该使用文件或文件夹浏览器的条件。这就是我无知的地方;我曾设想过类似这样的非工作代码:
private void browser(object sender, EventArgs e)
{
//cast sender as a textbox
TextBox tBox = (TextBox)sender;
object browser = null;
if (tBox.Tag.ToString().Equals("Folder"))
{
browser = new FolderBrowserDialog();
}
else
{
browser = new OpenFileDialog();
}
if (tBox.Text != "")//if the text box is not empty
{
//set the selected path to the text box's current contents (incase of accidental entry)
browser.FileName = tBox.Text;
}
if (browser.ShowDialog() == DialogResult.OK)
{
tBox.Text = browser.FileName;
}
}
我疯了,还是有办法实现我的想法?说清楚,我想知道是否有:
- 允许选择文件或文件夹的现有对象/方法,或
- 一种将对象动态重新定义为不同类型对象的方法
- 任何其他方式使用 1 方法来动态允许使用基于调用对象上定义的一些
Tag的OpenFileDialog或FileBrowserDialog。
【问题讨论】:
-
感谢@Sharped 澄清:我想知道这是否可以使用本机方法,没有任何 3rd 方代码,但根据您的链接,它看起来可能不是。
-
检查this question。答案谈到了通过 P/Invoke 执行此操作的机会。
标签: c# .net openfiledialog folderbrowserdialog