使用 C#,我希望我的应用程序返回文件夹(具有已知路径)是位于网络中还是位于我的计算机中。
我怎样才能做到这一点?
使用 C#,我希望我的应用程序返回文件夹(具有已知路径)是位于网络中还是位于我的计算机中。
我怎样才能做到这一点?
如果您正在谈论映射的网络驱动器,则可以使用DriveInfo
'DriveType
属性:
var driveInfo = new DriveInfo("S:\");
if(driveInfo.DriveType == DriveType.Network)
// do something
使用PathIsNetworkPath(pinvoke参考):
class Program
{
[DllImport("shlwapi.dll")]
private static extern bool PathIsNetworkPath(string pszPath);
static void Main(string[] args)
{
Console.WriteLine(PathIsNetworkPath("i:\Backup"));
}
}
根据@jgauffin 和@Daniel 的回答,你可以试试这个小技巧:
private static bool IsNetwork(String path)
{
if (path.StartsWith(@"\\"))
return true;
var dir = new DirectoryInfo(path);
var drive = new DriveInfo(dir.Root.ToString());
return drive.DriveType == DriveType.Network;
}
您可以使用以下方法获取文件夹的 UNC 路径。不完全是您正在寻找的东西,但可能有用
public static string GetUniversalPath(string folderPath)
{
if (String.IsNullOrEmpty(folderPath) || folderPath.IndexOf(":") > 1)
return folderPath;
if (folderPath.StartsWith("\\"))
{
return folderPath;
}
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT RemoteName FROM win32_NetworkConnection WHERE LocalName = '" + folderPath.Substring(0, 2) + "'");
foreach (ManagementObject managementObject in searcher.Get())
{
string remoteName = managementObject["RemoteName"] as String;
if (!String.IsNullOrEmpty(remoteName))
{
remoteName += folderPath.Substring(2);
return remoteName;
}
}
return folderPath;
}
从Shell Lightweight Utility API尝试以下操作:
class Class
{
[DllImport("shlwapi.dll")]
private static extern bool PathIsNetworkPath(string Path);
[STAThread]
static void Main(string[] args)
{
string strPath = "D:\\Temp\\tmpfile.txt";
bool blnIsLocalPath = IsLocalPath(strPath);
Console.WriteLine(blnIsLocalPath.ToString());
Console.ReadLine();
}
private static bool IsLocalPath(string Path)
{
return !PathIsNetworkPath(Path);
}
}
需要考虑的事项:
var dirInfo = new DirectoryInfo(yourPath);
var driveInfo = new DriveInfo(dirInfo.Root);
if (driveInfo.DriveType == DriveType.Network)
Console.WriteLine("Is a network drive!");