2010-09-17 20 views
128
string path = "C:/folder1/folder2/file.txt"; 

¿Qué objetos o métodos podría usar que me darían un resultado de folder2?Obtener el nombre de la carpeta de una ruta

+5

¿Usted está queriendo el último nombre de la carpeta así que si tenía C: \ carpeta1 \ carpeta2 \ carpeta3 \ archivo.txt, ¿quieres "carpeta3"? –

Respuesta

238

que probablemente utilice algo como:

string path = "C:/folder1/folder2/file.txt"; 
string lastFolderName = Path.GetFileName(Path.GetDirectoryName(path)); 

El llamado interior a GetDirectoryName devolverá la ruta completa, mientras la llamada externa a GetFileName() devolverá el último componente de la ruta - que será el nombre de la carpeta.

Este enfoque funciona si la ruta realmente existe o no. Sin embargo, este enfoque se basa en la ruta que inicialmente termina en un nombre de archivo. Si no se sabe si la ruta finaliza en un nombre de archivo o carpeta, entonces es necesario que verifique la ruta real para ver si existe un archivo/carpeta en la ubicación primero. En ese caso, la respuesta de Dan Dimitru puede ser más apropiada.

+0

Gracias LBushkin. Buen truco. He estado buscando esto. –

+81

Otra solución: return new DirectoryInfo (fullPath) .Name; –

+1

¡Genio, genio puro! ¡Gracias! –

-3
// For example: 
String[] filePaths = Directory.GetFiles(@"C:\Nouveau dossier\Source"); 
String targetPath = @"C:\Nouveau dossier\Destination"; 

foreach (String FileD in filePaths) 
{ 
    try 
    { 
    FileInfo info = new FileInfo(FileD); 
    String lastFolderName = Path.GetFileName(Path.GetDirectoryName(FileD)); 

    String NewDesFolder = System.IO.Path.Combine(targetPath, lastFolderName); 
    if (!System.IO.Directory.Exists(NewDesFolder)) 
    { 
     System.IO.Directory.CreateDirectory(NewDesFolder); 
    } 
    String destFile = System.IO.Path.Combine(NewDesFolder, info.Name); 

    File.Move(FileD, destFile); 

    // Try to move 
    Console.WriteLine("Moved"); // Success 
    } 
    catch (IOException ex) 
    { 
    Console.WriteLine(ex); // Write error 
    } 
} 
+1

¿Cómo se relaciona esto con la pregunta? – smiron

5

que utilizan este fragmento de código para obtener el directorio de un camino cuando ningún nombre de archivo está en el camino:

por ejemplo "c: \ tmp \ test \ visual";

string dir = @"c:\tmp\test\visual"; 
Console.WriteLine(dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, "")); 

Salida:

visual

+0

Puede simplemente hacer Path.GetFileName (dir) y devolverá el nombre de la carpeta muy bien. – jrich523

15

Prueba esto:

string filename = @"C:/folder1/folder2/file.txt"; 
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name; 
1

A continuación código ayuda a obtener el nombre de la carpeta única

 

public ObservableCollection items = new ObservableCollection(); 

    try 
      { 
       string[] folderPaths = Directory.GetDirectories(stemp); 
       items.Clear(); 
       foreach (string s in folderPaths) 
       { 
        items.Add(new gridItems { foldername = s.Remove(0, s.LastIndexOf('\\') + 1), folderpath = s }); 

       } 

      } 
      catch (Exception a) 
      { 

      } 
    public class gridItems 
    { 
     public string foldername { get; set; } 
     public string folderpath { get; set; } 
    } 
2
var fullPath = @"C:\folder1\folder2\file.txt"; 
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault(); 
-1

Ésta es feo, pero evita las asignaciones:

private static string GetFolderName(string path) 
{ 
    var end = -1; 
    for (var i = path.Length; --i >= 0;) 
    { 
     var ch = path[i]; 
     if (ch == System.IO.Path.DirectorySeparatorChar || 
      ch == System.IO.Path.AltDirectorySeparatorChar || 
      ch == System.IO.Path.VolumeSeparatorChar) 
     { 
      if (end > 0) 
      { 
       return path.Substring(i + 1, end - i - 1); 
      } 

      end = i; 
     } 
    } 

    if (end > 0) 
    { 
     return path.Substring(0, end); 
    } 

    return path; 
} 
4

simple & limpias. Sólo utiliza System.IO.FileSystem - funciona como un encanto:

string path = "C:/folder1/folder2/file.txt"; 
string folder = new DirectoryInfo(path).Name; 
1

DirectoryInfo hace el trabajo para despojar a nombre del directorio

string my_path = @"C:\Windows\System32"; 
DirectoryInfo dir_info = new DirectoryInfo(my_path); 
string directory = dir_info.Name; // System32 
Cuestiones relacionadas