Skip to content

Instantly share code, notes, and snippets.

@earlgreyxxx
Last active March 1, 2024 06:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save earlgreyxxx/c1b83fc5b15dc4663a30f7db9fc28c91 to your computer and use it in GitHub Desktop.
Save earlgreyxxx/c1b83fc5b15dc4663a30f7db9fc28c91 to your computer and use it in GitHub Desktop.
/********************************************************************
// 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