[C#]关于路径的几则笔记

时间:2023-03-09 07:33:52
[C#]关于路径的几则笔记

测试环境

本文基于windows下的操作

windows 7 x64

unity 5.3.7p4

获取文件的路径

比如一个文件的路径为:e:\3d\client\trunk\Product\Apps\Windows\v0007_1452\qxz_x86_dev.exe

我们想要获取它的路径,可以通过以下方式:

使用Path

var filePath = @"e:\3d\client\trunk\Product\Apps\Windows\v0007_1452\qxz_x86_dev.exe"
var dir = Path.GetDirectoryName(filePath);
//输出dir = e:\3d\client\trunk\Product\Apps\Windows\v0007_1452\

使用Directory

var filePath = @"e:\3d\client\trunk\Product\Apps\Windows\v0007_1452\qxz_x86_dev.exe"
var dir = new DirectoryInfo(filePath);
//输出dir = e:\3d\client\trunk\Product\Apps\Windows\v0007_1452\qxz_x86_dev.exe

但同的方法对于一个路径,结果则这样子的

//本身这串字符串就是路径不是文件
var srcPath = @"E:\\3dsn\\client\\trunk\\Product\\Apps\\NewApps\\v0007_1568_Windows";
//输出:E:\3dsn\client\trunk\Product\Apps\NewApps
var dir1 = Path.GetDirectoryName(srcPath);
//输出:E:\3dsn\client\trunk\Product\Apps\NewApps\v0007_1568_Windows
var dir2 = new DirectoryInfo(srcPath);

Unity和Windows的路径相反

在我之前的文章中也提到了这个差异:Unity的AssetDatabase路径格式

差异化表现如下:

windows下文件路径分隔符: \

Unity中文件路径分隔符: / (Unity中Application.datapath获取到的路径末尾不包含/)