Get the Correct File Paths in .NET Core [Code Snippet]
Here is a code snippet for getting the correct file paths in .NET core.
Join the DZone community and get the full member experience.
Join For FreeI run a custom blog engine I wrote myself on MVC 4 and as you would have thought it is on Windows hosting. I am re-writing my blog engine in .NET Core so that I can get it running on a Linux hosting as well. I am using Windows machine and Visual Studio Community Edition to write it and using a Ubuntu VM box to test it. My current blog uses SQL Server as a back-end but Linux does not support SQL Server and therefore I have to move to MySQL or any other No-SQL database available for Linux distros. For now, I will be saving everything on the disk in JSON format.
The problem comes when I switch from database to file system. Both Windows and Linux file systems are different, so when working I hard-coded the data folder which holds all the posts for my blog. I publish the solution and deploy it to Ubuntu VM. I started the server and it ended up showing me this error in the console.
Notice the path of the data folder in the above screenshot. The path I am referring in the code ends up with backslash which is not a UNIX format. Also, a thing to note here is that UNIX follows a strict naming convention, unlike Windows. For example, in Windows Data and data are same, but in UNIX they are not. Because I have hard-coded the path in my application while developing, it will end up in an error on UNIX machine.
To make the paths consistent in your application, I have to make use of the System.IO namespace Path class's Combine method. Combine method is an overloaded method. If you are hearing this method for the first time then make sure you read the documentation. This method renders the correct path based on the platform my code is executing. So instead of doing something like this.
var _posts = Directory.EnumerateFiles("Data\\Posts");
I have done something like this.
string posts = Path.Combine("Data", "Posts");
_files = Directory.EnumerateFiles(posts);
In short, if you are developing a .NET Core application targeting Windows along with UNIX and OSX, then make sure that you follow this approach to get the correct paths or else you will end up with an exception and your website inaccessible.Published at DZone with permission of Prashant Khandelwal, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments