C#windows形式避免for.pathlogical驱动()的循环 [英] C# windows form avoid for loop for directory.getlogicaldrives ()

查看:114
本文介绍了C#windows形式避免for.pathlogical驱动()的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello,
How to check in all PC hard drives, if a folder exists ?
I would like to control at one time and display a message that says yes, find in such disc.
In my example, the for condition displays as much message as it finds disk ...
How to search without a for loop ?
Thank you





我尝试过:





What I have tried:

<pre>          string[] str1 = Directory.GetLogicalDrives();
                    // for (initialization, condition, iteration)
                    for (int i = 0; i < str1.Length; ++i)
                    //  MessageBox.Show(str1[i]);

                    if (Directory.Exists(str1[i] + "Dossier1"))
                    {
                        MessageBox.Show("exists in : " + str1[i]);
                    }
                    else
                    {

                        MessageBox.Show("does not exist in : " + str1[i]);

                    }

推荐答案

1)将答案保存到循环之后,然后显示单个是/ /没有消息。



2)使用Linq方法:

1) Save the answer until after the loop, then display a single "yes / no" message.
Or
2) Use Linq methods:
string[] hasFolder = Directory.GetLogicalDrives().Where(d => Directory.Exists(Path.Combine(d, "Dossier"))).ToArray();



hasFolder数组包含包含您正在寻找的文件夹的所有驱动器。


The hasFolder array contains all the drives that contain the folder you are seeking.


Using System.Text;

StringBuilder sb = new StringBuilder();

(start of loop)
...
sb.AppendLine("xxx exists / does not exist on zzz");
...
(end of loop)

MessageBox.Show( sb.ToString() );


string[] drives = Directory.GetLogicalDrives().Where(d => Directory.Exists(Path.Combine(d, "Dossier"))).ToArray();
 string Résult = string.Join(", ", drives);
 if (Résult != "")
 {
     MessageBox.Show("exists");
 }
 else
 {
     MessageBox.Show("does not exist");
 }




Excellent, but can we do better!
thank you


这篇关于C#windows形式避免for.pathlogical驱动()的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆