0

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

BillyRain
  • 13
  • 2
  • 2
    Why don't you use a search engine before posting, make some try with the code found and finally ask for help if you have troubles? – Steve Jun 28 '15 at 14:37

1 Answers1

1

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.

Martin
  • 16,093
  • 1
  • 29
  • 48
  • Of course we could leave the problem about Permission Exceptions for a second question IE C:\System Volume Information and others – Steve Jun 28 '15 at 14:39
  • @Steve I don't seem to see any query about permissions in the OP's question. He asked how to search for files in sub-folders using C#. – Martin Jun 28 '15 at 14:41
  • @Steve I even dont think about permissions because I was searching for the basic code because I didn't find something usefull when I was searching. – BillyRain Jun 28 '15 at 14:55
  • 1
    My point was: Calling `Directory.GetFiles` on the root of C: drive will lead to an exception because the code will try to access one or more directories that are system protected. So if the OP uses this approach he/she should to plan how to handle the exceptions. But this is a bit pointless now. – Steve Jun 28 '15 at 14:58
  • @Steve Absolutely correct of course, this is likely to be a problem if the OP doesn't anticipate that circumstance. Further to Steve's point, the OP can look here to see how to anticipate permission problems and deal with them: http://stackoverflow.com/questions/172544/ignore-folders-files-when-directory-getfiles-is-denied-access – Martin Jun 28 '15 at 15:02