How to get files in a relative path in C#

.net, c#, directory, file

Solution

To make sure you have the application's path (and not just the current directory), use this:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getcurrentprocess.aspx

Now you have a `Process` object that represents the process that is running.

Then use `Process.MainModule.FileName`:

http://msdn.microsoft.com/en-us/library/system.diagnostics.processmodule.filename.aspx

Finally, use `Path.GetDirectoryName` to get the folder containing the .exe:

http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx

So this is what you want:

string folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\Archive\";
string filter = "*.zip";
string[] files = Directory.GetFiles(folder, filter);

(Notice that `"\Archive\"` from your question is now `@"\Archive\"`: you need the @ so that the `\` backslashes aren't interpreted as the start of an escape sequence)

Hope that helps!

Problem

If I have an executable called app.exe which is what I am coding in C#, how would I get files from a folder loaded in the same directory as the app.exe, using relative paths? This throws an illegal characters in path exception: ``` string [ ] files = Directory.GetFiles ( "\\Archive\\*.zip" ); ``` How would one do this in C#?

Original source