.Net中的Junction Points操作

Junction Points是NTFS v5+的新特性,功能和我们所熟知的UNIX中的文件夹软链接类似(与Windows中的文件夹快捷方式不同的是,它进行了路径重定向)。如在Vista中的C:\Documents and Settings 就是C:\Users的一个链接。然而,在Windows中并没有提供相关命令,只能编程通过API来实现。在CodeProject中有篇文章Manipulating NTFS Junction Points in .NET将相关API进行了封装,使得我们可以很容易的在.Net中进行相关操作。

由于我对WinAPI编程并不熟,这里就不更多介绍了,更多信息请访问原作者相关文章。这里仅转一下相关函数用法:

创建Junction Point

// Creates a Junction Point at
// C:\Foo\JunctionPoint that points to the directory C:\Bar.
// Fails if there is already a file,
// directory or Junction Point with the specified path.
JunctionPoint.Create(@"C:\Foo\JunctionPoint", @"C:\Bar",
false/*don't overwrite*/)

// Creates a Junction Point at C:\Foo\JunctionPoint that points to
// the directory C:\Bar.
// Replaces an existing Junction Point if found at the specified path.
JunctionPoint.Create(@"C:\Foo\JunctionPoint", @"C:\Bar", true/*overwrite*/)

注:不能对文件创建Junction Points.

删除Junction Point

// Delete a Junction Point at C:\Foo\JunctionPoint if it exists.
// Does nothing if there is no such Junction Point.
// Fails if the specified path refers to an existing file or
// directory rather than a Junction Point.
JunctionPoint.Delete(@"C:\Foo\JunctionPoint")

判断Junction Point是否存在

// Returns true if there is a Junction Point at C:\Foo\JunctionPoint.
// Returns false if the specified path refers to an existing file
// or directory rather than a Junction Point
// or if it refers to the vacuum of space.
bool exists = JunctionPoint.Exists(@"C:\Foo\JunctionPoint")

获取Junction Point所指向的实际地址

// Create a Junction Point for demonstration purposes whose target is C:\Bar.
JunctionPoint.Create(@"C:\Foo\JunctionPoint", @"C:\Bar", false)

// Returns the full path of the target of the Junction Point at
// C:\Foo\JunctionPoint.
// Fails if the specified path does not refer to a Junction Point.
string target = JunctionPoint.GetTarget(@"C:\Foo\JunctionPoint")

// target will be C:\Bar

注:这个函数有问题,对系统的权限要求过高,如果对系统盘的一些文件夹链接访问往往会报异常,我把它改了一下,新的代码如下:

Code
原文地址:https://www.cnblogs.com/TianFang/p/1381551.html