-2
 string l_path = "C:\\Windows\\System32\\calc.exe"
 string findString = "C:\\Windows";

 if (l_path.Contains(findString )) // C:\\Windows\\System32\\calc.exe
 {
     string l_EnvironmentVariable = l_path.Replace(findString , "WinDir");
 }

I want to get exact match from string statement. But when I check contains method its checking for any character match.. result (l_EnvironmentVariable) should be like "WINDIR\System32\calc.exe"

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
ND's
  • 2,155
  • 6
  • 38
  • 59
  • 3
    `C:\\Winodws` -> `C:\\Windows`? – Neijwiert Jun 21 '19 at 09:58
  • "i want to get exact match from string statement" what does this have to do with `Contains`? What are you trying to achieve and why is it not working? "its checking for any character match".. yes that is the `Contains` function literal purpose. – Joelius Jun 21 '19 at 10:02

1 Answers1

0

Let's Split each path into its parts (SplitPath):

private static string[] SplitPath(string value) {
  Queue<string> parts = new Queue<string>();

  for (DirectoryInfo diValue = new DirectoryInfo(value);
       diValue != null;
       diValue = diValue.Parent)
    parts.Enqueue(diValue.Name);

  return parts.Reverse().ToArray();
}

And then we can operate with these parts (compare and modify):

string l_path = "C:\\Windows\\System32\\calc.exe";
string findString = "C:\\Windows";

var l_path_parts = SplitPath(l_path);
var findString_parts = SplitPath(findString);

// If l_path starts from findString
var startsFrom = l_path_parts
  .Zip(findString_parts, (a, b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase))
  .All(item => item);

string l_EnvironmentVariable = startsFrom 
  ? Path.Combine(
      new string[] { Environment.GetEnvironmentVariable("WinDir") }.Concat(l_path_parts
        .Skip(findString_parts.Length))
        .ToArray())
  : l_path; 

Console.Write(l_EnvironmentVariable);

Outcome: (depends on WinDir environment variable; if it's D:\Windows)

D:\Windows\System32\calc.exe

Please, note that we compare paths by their parts, and that's why

string l_path = "C:\\WindowsToTest\\System32\\calc.exe"; 

fails to match C:\\Windows (since WindowsToTest != Windows) and we'll get

l_EnvironmentVariable == C:\WindowsToTest\System32\calc.exe
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • I have Environment variable list WinDir is not be constant – ND's Jun 21 '19 at 10:42
  • @John: then let's read `WinDir` environment variable: `Environment.GetEnvironmentVariable("WinDir")` instead of `"WinDir"`. See my edit; Another option is `"%WinDir%"` and let system put environment variable – Dmitry Bychenko Jun 21 '19 at 10:44