我有一个看起来像这样的文本文件:
Transfer
Transfer\Classified
Transfer\Keys
Transfer\Container
Transfer
我将文本文件的内容读入集合并使用for each
循环创建目录,如下所示:
BindingList<string> listFolders = new BindingList<string>();
foreach(string dirCreate in listFolders)
{
try
{
if(!Directory.Exists(dirCreate)){
Directory.CreateDirectory(String.Concat(txtRootFolder.Text,"\\",dirCreate));
}
else
{
MessageBox.Show(String.Format("{0} already exists",dirCreate));
}
}
catch(UnauthorizedAccessException msg)
{
MessageBox.Show(msg.Message);
}
问题:如果一个目录已经存在,MessageBox会弹出两次,我的意思是,一旦说目录已经存在,用户点击就可以了,它会弹出再一次,让用户再次点击OK。如何让它只弹出一次?
答案 0 :(得分:0)
我直接在代码中看到错误。
对于检查,你不认为你必须添加整个路径,而不仅仅是部分路径吗?
此:
if(!Directory.Exists(dirCreate)){
应该是:
if(!Directory.Exists(String.Concat(txtRootFolder.Text,"\\",dirCreate))){
当我在我的控制台应用程序中执行上述操作时,输出就像这样;
希望这有帮助。
[更新] WPF代码背后;
BindingList<string> paths;
public MainWindow()
{
InitializeComponent();
paths = new BindingList<string>();
paths.Add(@"Transfer");
paths.Add(@"Transfer\Classified");
paths.Add(@"Transfer\Keys");
paths.Add(@"Transfer\Container");
paths.Add(@"Transfer");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
foreach (string dirCreate in paths)
{
try
{
if (!Directory.Exists(String.Concat(txtFolderPath.Text, "\\", dirCreate)))
{
Directory.CreateDirectory(String.Concat(txtFolderPath.Text, "\\", dirCreate));
}
else
{
MessageBox.Show(String.Format("{0} already exists", dirCreate));
}
}
catch (UnauthorizedAccessException msg)
{
MessageBox.Show(msg.Message);
}
}
}
但仍然无法重现这个问题。
[更新2] WinForm代码
public partial class Form1 : Form
{
BindingList<string> paths;
public Form1()
{
InitializeComponent();
paths = new BindingList<string>();
paths.Add(@"Transfer");
paths.Add(@"Transfer\Classified");
paths.Add(@"Transfer\Keys");
paths.Add(@"Transfer\Container");
paths.Add(@"Transfer");
}
private void btnCreateFolders_Click(object sender, EventArgs e)
{
foreach (string dirCreate in paths)
{
try
{
string strDirectoryName = String.Concat(txtFolderPath.Text, "\\", dirCreate);
if (!Directory.Exists(strDirectoryName))
{
Directory.CreateDirectory(strDirectoryName);
}
else
{
MessageBox.Show(String.Format("{0} already exists", dirCreate));
}
}
catch (UnauthorizedAccessException msg)
{
MessageBox.Show(msg.Message);
}
}
}
}
仍然无法重现这个问题。