Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get files in a relative path in C#

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#?

like image 308
Joan Venge Avatar asked Jul 15 '10 20:07

Joan Venge


People also ask

What is relative path in C?

A relative path is a way to specify the location of a directory relative to another directory. For example, suppose your documents are in C:\Sample\Documents and your index is in C:\Sample\Index. The absolute path for the documents would be C:\Sample\Documents.

What is a relative path to a file?

Relative Path is the hierarchical path that locates a file or folder on a file system starting from the current directory. The relative path is different from the absolute path, which locates the file or folder starting from the root of the file system.

How do I find the relative path of a VS code?

Relative Path Extension for VS CodePress Ctrl+Shift+H (Mac: Cmd+Shift+H ) and start typing the file you want.


2 Answers

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!

like image 69
Kieren Johnstone Avatar answered Sep 23 '22 05:09

Kieren Johnstone


string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); string archiveFolder = Path.Combine(currentDirectory, "archive"); string[] files = Directory.GetFiles(archiveFolder, "*.zip"); 

The first parameter is the path. The second is the search pattern you want to use.

like image 36
Adam Lear Avatar answered Sep 22 '22 05:09

Adam Lear