wnetaddconnection2 networkcredential example c# .net network-drive

wnetaddconnection2 - networkcredential c# example



¿La forma más fácil en C#para averiguar si una aplicación se está ejecutando desde una unidad de red? (6)

Quiero saber por programación si mi aplicación se está ejecutando desde una unidad de red. ¿Cuál es la forma más sencilla de hacerlo? Debe admitir tanto las rutas UNC ( //127.0.0.1/d$ ) como las unidades de red asignadas (Z :).


En el caso de usar la ruta UNC es bastante simple: examine el nombre del host en UNC y pruebe que es localhost (127.0.0.1, :: 1, hostname, hostname.domain.local, direcciones IP de la estación de trabajo) o no.

Si la ruta no es UNC, extraiga la letra de la unidad y pruebe la clase DriveInfo para su tipo


Este es mi método actual de hacer esto, pero parece que debería haber una mejor manera.

private bool IsRunningFromNetworkDrive() { var dir = AppDomain.CurrentDomain.BaseDirectory; var driveLetter = dir.First(); if (!Char.IsLetter(driveLetter)) return true; if (new DriveInfo(driveLetter.ToString()).DriveType == DriveType.Network) return true; return false; }


Esto es para el caso de la unidad asignada. Puede usar la clase DriveInfo para averiguar si la unidad a es una unidad de red o no.

DriveInfo info = new DriveInfo("Z"); if (info.DriveType == DriveType.Network) { // Running from network }

Método completo y código de muestra.

public static bool IsRunningFromNetwork(string rootPath) { try { System.IO.DriveInfo info = new DriveInfo(rootPath); if (info.DriveType == DriveType.Network) { return true; } return false; } catch { try { Uri uri = new Uri(rootPath); return uri.IsUnc; } catch { return false; } } } static void Main(string[] args) { Console.WriteLine(IsRunningFromNetwork(System.IO.Path.GetPathRoot(AppDomain.CurrentDomain.BaseDirectory))); }


Reorganicé la solución de dotnetstep, que en mi opinión es mejor porque evita las excepciones cuando se pasa una ruta válida, y arroja una excepción si se pasa una ruta incorrecta, lo que no permite hacer una suposición de verdadero o falso.

//---------------------------------------------------------------------------------------------------- /// <summary>Gets a boolean indicating whether the specified path is a local path or a network path.</summary> /// <param name="path">Path to check</param> /// <returns>Returns a boolean indicating whether the specified path is a local path or a network path.</returns> public static Boolean IsNetworkPath(String path) { Uri uri = new Uri(path); if (uri.IsUnc) { return true; } DriveInfo info = new DriveInfo(path); if (info.DriveType == DriveType.Network) { return true; } return false; }

Prueba:

//---------------------------------------------------------------------------------------------------- /// <summary>A test for IsNetworkPath</summary> [TestMethod()] public void IsNetworkPathTest() { String s1 = @"//Test"; // unc String s2 = @"C:/Program Files"; // local String s3 = @"S:/"; // mapped String s4 = "ljöasdf"; // invalid Assert.IsTrue(RPath.IsNetworkPath(s1)); Assert.IsFalse(RPath.IsNetworkPath(s2)); Assert.IsTrue(RPath.IsNetworkPath(s3)); try { RPath.IsNetworkPath(s4); Assert.Fail(); } catch {} }


if (new DriveInfo(Application.StartupPath).DriveType == DriveType.Network) { // here }


DriveInfo m = DriveInfo.GetDrives().Where(p => p.DriveType == DriveType.Network).FirstOrDefault(); if (m != null) { //do stuff } else { //do stuff }