Convert a relative path that includes a drive letter to an absolute path for .NET file functions

风流意气都作罢 提交于 2019-12-04 15:49:50

问题


How can you convert a drive relative path such as D:test.xml into an absolute path that a function such as XDocument.Load() will accept. The D drive could have D:\data as its current working directory, for example, so D:test.xml would mean D:\data\test.xml . I've already tried such concoctions as D:.\test.xml .

Here is the error I get for something like D:test.xml: Invalid URI: A Dos path must be rooted, for example, 'c:\'


回答1:


You could use GetFullPath. For example:

// should return "D:\data\test.xml" if the current working dir is "D:\data"
string absolutePath = Path.GetFullPath("D:test.xml");



回答2:


You should simply use "test.xml" as a relative path and if the current folder is "D:\data", the full path would be resolved to "D:\Data\test.xml". This is also illustrated in the MSDN example for the Load() method: http://msdn.microsoft.com/en-us/library/bb343181.aspx

Please note that "driveLetter:fileName" is not a relative path in .Net. (Please read Update)

You can transform a relative path into a full path using Path.GetFullPath(), but you do not have to do that XDocument.Load(), since it will also accept relative paths.

Update LukeH, thanks for pointing this out! "driveLetter:fileName" are accepted by Path.GetFullPath() and are computed as relative paths to the current directory of the specified drive, as specified here.

The concept of current directory at drive level is inherited from the very old days of the DOS. Not necessarily a feature on which I would build modern applications.




回答3:


Path.GetFullPath can work. see the doc here



来源:https://stackoverflow.com/questions/4370891/convert-a-relative-path-that-includes-a-drive-letter-to-an-absolute-path-for-ne

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!