码迷,mamicode.com
首页 > Web开发 > 详细

.NET中Path类的一些常见用法

时间:2015-12-06 21:09:22      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

.NET为处理文件路径提供了一个Path类,利用该类可以方便的处理文件路径,如更改文件后缀,合并文件路径,改变文件的扩展名等。有一点需要注意的是,Path类本质上是对一个字符串进行处理,更改的只是该字符串,而不会影响实际的文件。下面是该类的一些常见用法示例:

 1             string filePath = @"C:\D\log\Receive\postedFile.txt";
 2             int padSpacesLength = 30;
 3             string newFilePath = string.Empty;
 4 
 5             //change original file extensiont form .txt to .jpg
 6             newFilePath = Path.ChangeExtension(filePath, ".jpg");
 7             Console.WriteLine("{0}{1}", "Change extension to jpg:".PadRight(padSpacesLength), newFilePath);
 8 
 9             string path1 = @"c:\temp";
10             string path2 = @"data";
11             string path3 = @"book.xml";
12             //combine path1 and path2 and path3
13             //note: the path to be combined should not be starts with slash(\)
14             newFilePath = Path.Combine(path1, path2, path3);
15             Console.WriteLine("{0}{1}", "Combine multiple paths:".PadRight(padSpacesLength), newFilePath);
16 
17             string fileName = Path.GetFileName(filePath);
18             Console.WriteLine("{0}{1}", "File Name:".PadRight(padSpacesLength), fileName);
19 
20             //get directory name of this file
21             string directoryName = Path.GetDirectoryName(filePath);
22             Console.WriteLine("{0}{1}", "Directory name of file:".PadRight(padSpacesLength), directoryName);
23 
24             //get the file name without file extension
25             string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);
26             Console.WriteLine("{0}{1}", "File name without extension:".PadRight(padSpacesLength), fileNameWithoutExtension);
27 
28             //just to get the extension name of this file
29             string extensionName = Path.GetExtension(filePath);
30             Console.WriteLine("{0}{1}", "The extension name of file:".PadRight(padSpacesLength), extensionName);
31 
32             //get the temp folder of environment
33             string tempPath = Path.GetTempPath();
34             Console.WriteLine("{0}{1}", "The temp path of enviornment:".PadRight(padSpacesLength), tempPath);
35 
36             //get a tempfile name
37             string tempFileName = Path.GetTempFileName();
38             Console.WriteLine("{0}{1}", "A temp file name:".PadRight(padSpacesLength), tempFileName);

输出结果:

技术分享

.NET中Path类的一些常见用法

标签:

原文地址:http://www.cnblogs.com/kuillldan/p/5024342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!