本文介绍了检查文件是否是真实的还是符号链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法告诉使用C#如果文件是真实的还是符号链接?
Is there a way to tell using C# if a file is real or a symbolic link?
我已经通过MSDN文档W32挖(http://msdn.microsoft.com/en-us/library/aa364232(VS.85).aspx),而找不到选中此事情。我使用CreateSymbolicLink从这里,和它的正常工作。
I've dug through the MSDN W32 docs (http://msdn.microsoft.com/en-us/library/aa364232(VS.85).aspx), and can't find anything for checking this. I'm using CreateSymbolicLink from here, and it's working fine.
推荐答案
我有一些的符号链接,让您可以:
I have some source code for symlinks posted on my blog that will allow you to:
- 创建符号链接
- 检查路径是否是一个符号链接
- 检索符号链接的目标
它也包含了NUnit测试的情况下,您可能希望延长。
It also contains NUnit test cases, that you may wish to extend.
肉香位的是:
private static SafeFileHandle getFileHandle(string path)
{
return CreateFile(path, genericReadAccess, shareModeAll, IntPtr.Zero, openExisting,
fileFlagsForOpenReparsePointAndBackupSemantics, IntPtr.Zero);
}
public static string GetTarget(string path)
{
SymbolicLinkReparseData reparseDataBuffer;
using (SafeFileHandle fileHandle = getFileHandle(path))
{
if (fileHandle.IsInvalid)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
int outBufferSize = Marshal.SizeOf(typeof(SymbolicLinkReparseData));
IntPtr outBuffer = IntPtr.Zero;
try
{
outBuffer = Marshal.AllocHGlobal(outBufferSize);
int bytesReturned;
bool success = DeviceIoControl(
fileHandle.DangerousGetHandle(), ioctlCommandGetReparsePoint, IntPtr.Zero, 0,
outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero);
fileHandle.Close();
if (!success)
{
if (((uint)Marshal.GetHRForLastWin32Error()) == pathNotAReparsePointError)
{
return null;
}
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
reparseDataBuffer = (SymbolicLinkReparseData)Marshal.PtrToStructure(
outBuffer, typeof(SymbolicLinkReparseData));
}
finally
{
Marshal.FreeHGlobal(outBuffer);
}
}
if (reparseDataBuffer.ReparseTag != symLinkTag)
{
return null;
}
string target = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer,
reparseDataBuffer.PrintNameOffset, reparseDataBuffer.PrintNameLength);
return target;
}
这就是:
- 使用
-
的DeviceIoControl()
以获得重分析点数据(注:这可能是一个结点) - 查看rel=\"nofollow\">返回href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff552012%28v=vs.85%29.aspx\"的检查。该会告诉你,如果它是一个结点或符号链接。这可能是所有你想做的事。
- Open the file with
CreateFile()
- Call
DeviceIoControl()
to get the reparse point data (NOTE: it could be a junction point!) - Check out the returned data structure to inspect. The reparse tag will tell you if it is a junction point or symbolic link. This may be all you want to do.
这篇关于检查文件是否是真实的还是符号链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!