未加星标

Get the Correct File Paths in .Net Core [Code Snippet]

字体大小 | |
[系统(windows) 所属分类 系统(windows) | 发布者 店小二05 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

I 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.

本文系统(windows)相关术语:三级网络技术 计算机三级网络技术 网络技术基础 计算机网络技术

分页:12
转载请注明
本文标题:Get the Correct File Paths in .Net Core [Code Snippet]
本站链接:http://www.codesec.net/view/479840.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 系统(windows) | 评论(0) | 阅读(57)