Using Directory.Getfiles with absolute path

Hi, I wonder if you guys could help.

I am writing an application that will run on several servers and, therefore, multiple IPs and instead of using the exact structure of IP and directories, I would just like to β€œbacktrack” from the folder where the application is really running, For example ....

Folder structure

\ controls \ ---- This contains an aspx file that will check if the xml file exists in the blogengine folder.

\ blogengine \ This should contain xml files

The code I use is ......

string[] filePaths = Directory.GetFiles(@"\\94.175.237.35\inetpub$\wwwroot\mytest\BlogEngine\", "*.xml"); 

That will find files on a specific server, but I need to find files in relation to the server on which the application is running, so I do not need to change the path to the file. So i need something like

 string[] filePaths = Directory.GetFiles(@"..\BlogEngine\", "*.xml"); 

But I can not find the correct syntax to do this?

Somebody knows?

Thanks in advance Craig

+4
source share
3 answers

Use the Server.MapPath() method to map the relative path (based on the current directory or website root) to the absolute path available.

For instance:

 string folderPath = Server.MapPath("~/BlogEngine"); string[] filePaths = Directory.GetFiles(folderPath, "*.xml"); 

The tilde symbol represents the root of your website, if you specify a relative path, then it will be resolved relative to the directory where your ASP.NET page is located.

+6
source

In an ASP.Net application, you can call Server.MapPath("~/path") to resolve the disk path relative to the application root directory.

+1
source

Use Path.GetFullPath to get the absolute path from your relative path.

So your code will look like this:

 string[] filePaths = Directory.GetFiles(Path.GetFullPath(@"..\BlogEngine\"), "*.xml"); 
+1
source

Source: https://habr.com/ru/post/1433610/


All Articles