简体   繁体   English

c#从文件名搜索并获取路径

[英]c# Search and get path from Filename

I want to look for a file inside the existing logical drives connected, but when I do that, i end up with an string[], which i really don't know how to handle... So what I'm trying to do here, is search in the "hard disc" drives which normally have the format FAT32 or NTFS... (please tell me if there are any others often used) And then, i get the "letter" for that drive, and tries to search for the csgo.exe file from there. 我想在已连接的现有逻辑驱动器中查找文件,但是当我这样做时,我最终得到的是string [],我真的不知道该如何处理...所以我想做的是在这里,搜索通常具有FAT32或NTFS格式的“硬盘”驱动器...(请告诉我是否经常使用其他任何驱动器)然后,我得到该驱动器的“字母”,并尝试从那里搜索csgo.exe文件。 And you can probably figure out the rest... 您可能可以找出其余的...

Here's my code... 这是我的代码...

if (d.DriveFormat.ToString() == "FAT32" || d.DriveFormat.ToString() == "NTFS")
{
    string StartDir = d.RootDirectory.ToString();
    String[] csgofile = Directory.GetFiles(StartDir, "csgo.exe", SearchOption.TopDirectoryOnly);
    foreach (String file in csgofile)
    {
        if (File.Exists(file))
        {
            MessageBox.Show("Drive: " + StartDir + ", CS:GO Path: " + file, "Path Found!");
        }
    }
}

Your code is correct, you will end up on string[] since that is the variable you declare on this line: 您的代码是正确的,您将以string []结尾,因为这是您在以下行中声明的变量:

String[] csgofile = Directory.GetFiles(StartDir, "test.txt", SearchOption.TopDirectoryOnly);

If the file doesn't exist, and you debug it, it will look like 如果该文件不存在,并且您对其进行了调试,它将看起来像

csgofile|{string[0]}

If it gets the file successfully, it will be: 如果成功获取文件,它将是:

csgofile|{string[1]}

Please take note that you are just searching the file on TopDirectoryOnly so make sure the file really exist in your the drive you are searching. 请注意,您只是在TopDirectoryOnly上搜索文件,因此请确保该文件确实存在于要搜索的驱动器中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM