如果c#中给定文件夹中不存在指定文件,如何导航到子文件夹?

时间:2017-09-01 09:50:39

标签: c# filepath

我有一个文件路径,

string filepath = "E:\Dotnet\VSPackage1\ItemTemplates";

现在我想查看VSPackage1文件夹中是否存在名为“Unit.exe”的文件,如果“Unit.exe”不存在,那么我必须导航到ItemTemplates文件夹。

如何以编程方式实现此目的?在此先感谢。

2 个答案:

答案 0 :(得分:3)

您可以使用String.Splitforeach循环来实现此目的:

string filepath = "E:\\Dotnet\\VSPackage1\\ItemTemplates";
string[] Folders = filepath.Split('\\');
string newPath = "";
string yourFilename = "Unit.exe";

foreach (var folder in Folders)
{
    newPath += folder + "\\";
    if (File.Exists(newPath + yourFilename))
    {
       MessageBox.Show("File found");
       break;
    }
}
找到文件时,

break会中断foreach循环。因此,迭代将遵循以下顺序:

E:\\Unit.exe  
//Check for file, if present message will be shown "File found" and loop will be broken

E:\\Dotnet\\Unit.exe  
//Check for file, if present message will be shown "File found" and loop will be broken

E:\\Dotnet\\VSPackage1\\Unit.exe  
//Check for file, if present message will be shown "File found" and loop will be broken

E:\\Dotnet\\VSPackage1\\ItemTemplates\\Unit.exe  
//Check for file, if present message will be shown "File found" and loop will be broken

答案 1 :(得分:1)

您可以执行以下操作:

string filepath = "E:\\Dotnet\\VSPackage1\\ItemTemplates";

DirectoryInfo di = new DirectoryInfo(filepath);
FileInfo[] rgFiles = di.GetFiles("*.exe");

foreach (FileInfo fi in rgFiles)
{
    if (File.Exists(filepath + @"\Unit.exe"))
    {
        //do Something
    }           
}