我有一个文件路径,
string filepath = "E:\Dotnet\VSPackage1\ItemTemplates";
现在我想查看VSPackage1文件夹中是否存在名为“Unit.exe”的文件,如果“Unit.exe”不存在,那么我必须导航到ItemTemplates文件夹。
如何以编程方式实现此目的?在此先感谢。
答案 0 :(得分:3)
您可以使用String.Split
和foreach
循环来实现此目的:
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
}
}