una saber ruta net existe example directorio comprobar carpeta buscar borrar archivo c# windows vb.net .net-4.0

ruta - saber si existe un archivo c#



Compruebe si el directorio existe en Network Drive (4)

Estoy tratando de detectar si el directorio existe, pero en esta situación particular, mi directorio es una ubicación de red. My.Computer.FileSystem.DirectoryExists(PATH) de VB.NET My.Computer.FileSystem.DirectoryExists(PATH) y el System.IO.Directory.Exists(PATH) más general, y en ambos casos, la respuesta del sistema es falsa. Comprobé y existe la RUTA, puedo verla en la carpeta Mi PC. Si depuro el programa y miro la variable My.Computer.FileSystem.Drives , la ubicación de la red no aparece en esa lista.

ACTUALIZACIÓN: revisé y en Windows XP la respuesta es verdadera, pero no en Windows 7.

ACTUALIZACIÓN2: Probé ambas soluciones propuestas, pero todavía tengo el mismo problema, en la imagen a continuación verá que puedo acceder usando el Explorador pero mi programa no. La función GetUNCPath devuelve una ruta válida (sin errores), pero Directory.Exists stil devuelve false.

También probé con la ruta UNC "// Server / Images"; mismo resultado.

ACTUALIZACIÓN3: Si no puedo enlazar con una unidad de red, ¿cómo puedo enlazar directamente a la ruta UNC ?. Descubrí que si ejecuto VS en modo normal, funciona, pero mi software debe ejecutarse en modo administrador. Entonces, ¿hay alguna manera de verificar la existencia de un directorio de red como administrador?


Además, tuve que hacer una comprobación de ''Exists'' en los recursos compartidos de la red que podían aparecer, pero la cuenta no tenía permiso de acceso, por lo que Directory.Exists devolvería False.

Varias soluciones publicadas no funcionaron para mí, así que aquí está el mío:

public static bool DirectoryVisible(string path) { try { Directory.GetAccessControl(path); return true; } catch (UnauthorizedAccessException) { return true; } catch { return false; } }


Cuando utiliza System.IO.Directory.Exists , solo le permite saber que no pudo encontrar el directorio, pero esto podría deberse a que el directorio no existe o porque el usuario no tiene suficientes derechos de acceso al directorio.

Para resolver esto, agregamos una prueba secundaria después de Directory.Exists no logra obtener el motivo real de la ausencia del directorio y lo hemos incluido en un método global que se usa en lugar del método estándar Directory.Exists :

'''''' <summary> '''''' This method tests to ensure that a directory actually does exist. If it does not, the reason for its '''''' absence will attempt to be determined and returned. The standard Directory.Exists does not raise '''''' any exceptions, which makes it impossible to determine why the request fails. '''''' </summary> '''''' <param name="sDirectory"></param> '''''' <param name="sError"></param> '''''' <param name="fActuallyDoesntExist">This is set to true when an error is not encountered while trying to verify the directory''s existence. This means that '''''' we have access to the location the directory is supposed to be, but it simply doesn''t exist. If this is false and the directory doesn''t exist, then '''''' this means that an error, such as a security error, was encountered while trying to verify the directory''s existence.</param> Public Function DirectoryExists(ByVal sDirectory As String, ByRef sError As String, Optional ByRef fActuallyDoesntExist As Boolean = False) As Boolean '' Exceptions are partially handled by the caller If Not IO.Directory.Exists(sDirectory) Then Try Dim dtCreated As Date '' Attempt to retrieve the creation time for the directory. '' This will usually throw an exception with the complaint (such as user logon failure) dtCreated = Directory.GetCreationTime(sDirectory) '' Indicate that the directory really doesn''t exist fActuallyDoesntExist = True '' If an exception does not get thrown, the time that is returned is actually for the parent directory, '' so there is no issue accessing the folder, it just doesn''t exist. sError = "The directory does not exist" Catch theException As Exception '' Let the caller know the error that was encountered sError = theException.Message End Try Return False Else Return True End If End Function


Si el UAC está activado, las unidades de red asignadas solo existen "de manera predeterminada" en la sesión que están asignadas: Normal o elevada. Si asigna una unidad de red desde el explorador, luego ejecute VS como administrador, la unidad no estará allí.

Debe habilitar lo que MS llama "conexiones enlazadas": HKEY_LOCAL_MACHINE / Software / Microsoft / Windows / CurrentVersion / Policies / System: EnableLinkedConnections (REG_DWORD) = 0x1

Información de fondo sobre "dos sesiones de inicio de sesión" con UAC: http://support.microsoft.com/kb/937624/en-us


public static class MappedDriveResolver { [DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int WNetGetConnection([MarshalAs(UnmanagedType.LPTStr)] string localName, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName, ref int length); public static string GetUNCPath(string originalPath) { StringBuilder sb = new StringBuilder(512); int size = sb.Capacity; // look for the {LETTER}: combination ... if (originalPath.Length > 2 && originalPath[1] == '':'') { // don''t use char.IsLetter here - as that can be misleading // the only valid drive letters are a-z && A-Z. char c = originalPath[0]; if ((c >= ''a'' && c <= ''z'') || (c >= ''A'' && c <= ''Z'')) { int error = WNetGetConnection(originalPath.Substring(0, 2), sb, ref size); if (error == 0) { DirectoryInfo dir = new DirectoryInfo(originalPath); string path = Path.GetFullPath(originalPath).Substring(Path.GetPathRoot(originalPath).Length); return Path.Combine(sb.ToString().TrimEnd(), path); } } } return originalPath; } }

Para usarlo, pase una ruta de la carpeta de red, convierta a la ruta de la carpeta UNC y vea si existe la carpeta:

File.Exists(MappedDriveResolver.GetUNCPath(filePath));

Editar:

Vi su segunda edición y la única diferencia (en mi Windows 7) cuando veo una unidad de red veo Computadora> Imágenes (// xyzServer) . ¿El nombre de su equipo es Equipo ? es ese equipo en español? ¿esa es tu PC? Traté de reproducir tu problema pero funciona para mí: