Using c # how to find out if a folder is online or not

Using C #, I would like my application to return whether the folder (with the already known path) is on the network or on my computer.

How can i do this?

+6
source share
6 answers

If you are talking about a mapped network drive, you can use the DriveInfo DriveType property:

 var driveInfo = new DriveInfo("S:\"); if(driveInfo.DriveType == DriveType.Network) // do something 
+6
source

Original answer from another SO question. Check if the path is on the network .

Use PathIsNetworkPath (pinvoke link ):

 class Program { [DllImport("shlwapi.dll")] private static extern bool PathIsNetworkPath(string pszPath); static void Main(string[] args) { Console.WriteLine(PathIsNetworkPath("i:\Backup")); } } 
+4
source

Based on the answers of @jgauffin and @Daniel, you can try this little hack:

 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; } 
+3
source
 var dirInfo = new DirectoryInfo(yourPath); var driveInfo = new DriveInfo(dirInfo.Root); if (driveInfo.DriveType == DriveType.Network) Console.WriteLine("Is a network drive!"); 
0
source

Try the following from the 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); } } 

What to consider:

  • Paths starting with two backslash characters (\) are interpreted as UNC (UNC) paths.
  • Paths starting with a colon followed by a colon (:) are interpreted as a mapped network drive. However, PathIsNetworkPath cannot recognize a network drive mapped to a drive letter through the MS MSOS DOS SUBST command or the DefineDosDevice function.
0
source

You can use the following method to get the UNC path for the folder. Not exactly what you are looking for, but may be useful

  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; } 
0
source

Source: https://habr.com/ru/post/894720/


All Articles