淘宝店铺装修做代码的网站,网站管理办法制度,深圳公司注册下来有哪些资料,wordpress继续阅读插件咨询区 David Boike请问在 C# 中是否有好的方式判断 path 是在本地还是在远程,我想到了用 UNC 属性来判断#xff0c;比如下面的代码#xff1a;new Uri(path).IsUnc但这代码也有一定的问题,它会误判下面的 path 格式。\\machinename\sharename\directory
\\10.12.34.56\shar… 咨询区 David Boike请问在 C# 中是否有好的方式判断 path 是在本地还是在远程,我想到了用 UNC 属性来判断比如下面的代码new Uri(path).IsUnc但这代码也有一定的问题,它会误判下面的 path 格式。\\machinename\sharename\directory
\\10.12.34.56\sharename\directory上面这两种格式也是在本地而不是远程。回答区 Stephen我是借助 Shlwapi.dll 这个 win32 api 来实现的可以用它来判断当前的 path 来自于 drivers 还是 UNC。private static bool IsLocalPath(String path)
{if (!PathIsUNC(path)){return !PathIsNetworkPath(path);}Uri uri new Uri(path);return IsLocalHost(uri.Host); // Refer to Davids answer
}[DllImport(Shlwapi.dll)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PathIsNetworkPath(String pszPath);[DllImport(Shlwapi.dll)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PathIsUNC(String pszPath);Eric Rosenberger可以通过 path 的 host 来判断当前是否为 回路地址我不知道这是否是最高效的解决方案但适合我。IPAddress[] host;IPAddress[] local;bool isLocal false;host Dns.GetHostAddresses(uri.Host);local Dns.GetHostAddresses(Dns.GetHostName());foreach (IPAddress hostAddress in host){if (IPAddress.IsLoopback(hostAddress)){isLocal true;break;}else{foreach (IPAddress localAddress in local){if (hostAddress.Equals(localAddress)){isLocal true;break;}}if (isLocal){break;}}}Renato Heeb我是通过 path 的 DriverInfo 的 DriverType Network 来判断当前是否为远程。public static bool IsLocal(DirectoryInfo dir){foreach (DriveInfo d in DriveInfo.GetDrives()){if (string.Compare(dir.Root.FullName, d.Name, StringComparison.OrdinalIgnoreCase) 0) //[drweb86] Fix for different case.{return (d.DriveType ! DriveType.Network);}}throw new DriveNotFoundException();}点评区 这场景我还真的遇到过曾经给医院内网部署桌面程序时需要读取局域网共享文件中的 txt 文本三位大佬提供的方案很全面学习了。