正 文

用.NET的Path类简化普通编程任务


www.7dspace.com  更新日期:2005-12-2 3:08:35  七度空间


路径要在一个字符串变量里设置,而Path类将它用作其代码里所有操作的基础。执行这段代码就会得到下面的结果:

Path has an extension: .txt.
The path contains root information: c:\.
The filename is test.txt.
The full path is c:\builder\test\test.txt.
The location for temporary files is C:\Windows\Temp\.
The following temp file is available: C:\Windows\Temp\tmpC7.tmp .
The set of invalid characters in a path is:
"


|

对于使用VB.NET编程的人来说,句法是类似的。下面就是VB.NET的代码:

Imports System.IO
Dim pth As String = "c:\\builder\\test\\test.txt"
Dim c As Char
If (Path.HasExtension(pth)) Then
Console.WriteLine("Path has an extension: {0}.", Path.GetExtension(pth))
Else
Console.WriteLine("Path has no extension: {0}.",
Path.GetFileNameWithoutExtension(pth))
End If
If (Path.IsPathRooted(pth)) Then
Console.WriteLine("The path contains root information: {0}.",
Path.GetPathRoot(pth))
End If
Console.WriteLine("The filename is {0}.", Path.GetFileName(pth))
Console.WriteLine("The full path is {0}.", Path.GetFullPath(pth))
Console.WriteLine("The location for temporary files is {0}.",
Path.GetTempPath())
Console.WriteLine("The following temp file is available: {0} .",
Path.GetTempFileName())
Console.WriteLine("The set of invalid characters in a path is:")
For Each c In Path.InvalidPathChars
Console.WriteLine(c)
Next c

在代码示例里,要注意Path类在使用的时候没有被实例化。它只是简单地被调用(利用正确的方法),因为它是一个带有静态方法的实例类。此外,代码的最后一部分利用了Path类的InvalidPathChars属性。现在让我们来看看其他可用的属性:

    * AltDirectorySeparatorChar:用来分隔路径里目录的备用路径字符。在所有的Windows平台里它是除号(/)。

    * DirectorySeparatorChar:用来分隔路径里目录的路径字符。在所有的Windows平台上是反斜杠(\)。

    * InvalidPathChars:一组不被允许用在路径里的字符。

    * PathSeparator:用来分隔环境变量里路径字符串的字符。在Windows平台上是分号(;)。

    * VolumeSeparatorChar:用于将路径同卷分开的字符。在Windows平台上是冒号(:)。

这些属性允许你迅速和很容易地掌握平台的特性。这就让在文件路径里使用正确的分隔符并避免插入不正确的字符变容易了。这些属性能够用下面C#代码访问到,这段代码可以被加到前面的例子里:

Console.WriteLine("Path separator: {0}.", Path.PathSeparator);
Console.WriteLine("Directory separator: {0}.", Path.DirectorySeparatorChar);
Console.WriteLine("Volume separator: {0}.", Path.VolumeSeparatorChar);

下面就是相应的VB.NET代码:

Console.WriteLine("Path separator: {0}.", Path.PathSeparator)
Console.WriteLine("Directory separator: {0}.", Path.DirectorySeparatorChar)
Console.WriteLine("Volume separator: {0}.", Path.VolumeSeparatorChar)

在我的系统里,代码生成了下面的输出:

Path separator: ;
Directory separator: \.
Volume separator: :.

以上就是用于Windows平台的标准字符。

受欢迎的增加

Path类是一个加到你工具箱里的受欢迎的工具。它让操控文件路径不再需要使用字符串变量和相关的方法。这就让你可以把宝贵的时间花在别的地方。

本文作者:Tony Patton的职业生涯开始于应用程序开发员,并已经获得了Java、VB、Lotus和XML的认证,以增加其专业知识。

2页,页码:[1] [2] 

上一篇:在对象中执行Icomparable接口
下一篇:使用类厂方法来实例化对象
作者:Tony Patton  来源:开发者在线 ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐