Last active
March 1, 2024 06:35
-
-
Save earlgreyxxx/c1b83fc5b15dc4663a30f7db9fc28c91 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/******************************************************************** | |
// require ... | |
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Text.RegularExpressions; | |
*********************************************************************/ | |
public static string[] Where(string CommandName) | |
{ | |
//環境変数%PATH%取得し、カレントディレクトリを連結し、IEnumerable<string>を取得 | |
var dirPathList = | |
Environment | |
.ExpandEnvironmentVariables(Environment.GetEnvironmentVariable("PATH")) | |
.Split(new char[] { ';' }) | |
.Prepend(Directory.GetCurrentDirectory()); | |
//正規表現に使用するため、%PATHEXT%の取得・ピリオド文字の変換及び配列への格納 | |
var pathext = Environment.GetEnvironmentVariable("PATHEXT").Replace(".", @"\.").Split(new Char[] { ';' }); | |
//検索するファイル名の正規表現 | |
var regex = new Regex( | |
$"^{CommandName}(?:{String.Join("|", pathext)})?$", | |
RegexOptions.IgnoreCase | |
); | |
// 各ディレクトリを存在チェックし、実行可能ファイルを検索し、SelectManyで平坦化する。 | |
return | |
dirPathList | |
.Where(dirPath => Directory.Exists(dirPath)) | |
.SelectMany(dirPath => Directory.GetFiles(dirPath).Where(file => regex.IsMatch(Path.GetFileName(file)))) | |
.ToArray(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment