使用C#或其他.NET语言确定文件路径字符串是在本地计算机还是远程服务器上的最佳方法是什么?
可以使用以下内容确定路径字符串是否为UNC:
new Uri(path).IsUnc
Run Code Online (Sandbox Code Playgroud)
这适用于以C:\或其他驱动器号开头的路径,但是路径如下:
\\machinename\sharename\directory
\\10.12.34.56\sharename\directory
Run Code Online (Sandbox Code Playgroud)
...两者都引用本地机器 - 这些是UNC路径但仍然是本地路径.
Ren*_*eeb 21
这就是我做到的.
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();
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ger 17
不知道是否有更有效的方法,但它似乎对我有用:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Dav*_*vid 12
.NET 3.5版本的Eric的答案,额外检查主机是否存在:
private bool IsLocalHost(string input)
{
IPAddress[] host;
//get host addresses
try { host = Dns.GetHostAddresses(input); }
catch (Exception) { return false; }
//get local adresses
IPAddress[] local = Dns.GetHostAddresses(Dns.GetHostName());
//check if local
return host.Any(hostAddress => IPAddress.IsLoopback(hostAddress) || local.Contains(hostAddress));
}
Run Code Online (Sandbox Code Playgroud)
小智 7
以下内容适用于映射驱动器和UNC路径.
private static bool IsLocalPath(String path)
{
if (!PathIsUNC(path))
{
return !PathIsNetworkPath(path);
}
Uri uri = new Uri(path);
return IsLocalHost(uri.Host); // Refer to David's 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);
Run Code Online (Sandbox Code Playgroud)
小智 5
以下是我解决类似需求的方法.
internal static bool IsFileRemote(string path)
{
if (String.IsNullOrEmpty(path))
{
return false;
}
if (new Uri(path).IsUnc)
{
return true;
}
if (new DriveInfo(path).DriveType == DriveType.Network)
{
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25869 次 |
| 最近记录: |