Search code examples
c#.netregistryconsole-application

C# searching and getting Absolute Path of Software


I am new to C# and I want to create a little Autorun Manager in a Console Application. To do that I want to read from the console a keyword like "Steam" and my programm should search on "C:\" and in all subdirectories for a folder called like my keyword but as I say I have no Idea how I can search in all subdirectories.

Thats a little code sample with steam how I would write in registry

//filePath would be the Path of the .EXE file that was found    
string filePath = "\"C:\\Programme\\Steam\\Steam.exe\""; 
string autostartPath = @"Software\Microsoft\Windows\CurrentVersion\Run\";
RegistryKey autostart = Registry.CurrentUser.OpenSubKey(autostartPath, true);
autostart.SetValue("Steam", filePath);

If someone know how to search in all subdirectories and find the correct .exe file.

I would be really grateful for a code sample.

Thanks in advance


Solution

  • This is relatively easy using Directory.GetFiles():

    string[] Files = Directory.GetFiles(@"C:\", "steam.exe", SearchOption.AllDirectories);
    

    This will search for all files matching the name steam.exe on C:\ and in all subdirectories, and return all the results as an array of string.

    Note that you can use wildcards in the name, so that "steam*.exe" will return all files starting with steam with an exe extension.

    If you need to, add using System.IO to the top of your class to import the IO namespace.