如何使用C#判断文件是否在已经通过SUBST或位于用户文件夹中的文件夹中?
using System.Runtime.InteropServices;
[DllImport("kernel32.dll", SetLastError=true)]
static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax);
public static bool IsSubstedPath(string path, out string realPath)
{
StringBuilder pathInformation = new StringBuilder(250);
string driveLetter = null;
uint winApiResult = 0;
realPath = null;
try
{
// Get the drive letter of the path
driveLetter = Path.GetPathRoot(path).Replace("\\", "");
}
catch (ArgumentException)
{
return false;
//<------------------
}
winApiResult = QueryDosDevice(driveLetter, pathInformation, 250);
if(winApiResult == 0)
{
int lastWinError = Marshal.GetLastWin32Error(); // here is the reason why it fails - not used at the moment!
return false;
//<-----------------
}
// If drive is substed, the result will be in the format of "\??\C:\RealPath\".
if (pathInformation.ToString().StartsWith("\\??\\"))
{
// Strip the \??\ prefix.
string realRoot = pathInformation.ToString().Remove(0, 4);
// add backshlash if not present
realRoot += pathInformation.ToString().EndsWith(@"\") ? "" : @"\";
//Combine the paths.
realPath = Path.Combine(realRoot, path.Replace(Path.GetPathRoot(path), ""));
return true;
//<--------------
}
realPath = path;
return false;
}
using System.Runtime.InteropServices;
否则将会出现错误。 - gg89我认为你有几个选择--
通过System.Management类: http://briancaos.wordpress.com/2009/03/05/get-local-path-from-unc-path/
或者
通过调用此MAPI函数: ScUNCFromLocalPath http://msdn.microsoft.com/en-us/library/cc842520.aspx
subst
是一个 DOS 命令,它将为目录创建别名(例如,subst T: C:\workareas
将创建一个指向 C:\workareas 的新驱动器)。对于用户文件夹,我想找出它是否干净地位于C:\Documents and Settings\%username%
。 - petejamd