Obtener el nombre de la carpeta de una ruta
string path = "C:/folder1/folder2/file.txt";
¿Qué objetos o métodos podría usar que me den un resultado de folder2
?
10 answers
Probablemente usaría algo como:
string path = "C:/folder1/folder2/file.txt";
string lastFolderName = Path.GetFileName( Path.GetDirectoryName( path ) );
La llamada interna a GetDirectoryName
devolverá la ruta completa, mientras que la llamada externa a GetFileName()
devolverá el último componente de ruta - que será el nombre de la carpeta.
Este enfoque funciona independientemente de que el camino exista o no. Este enfoque, sin embargo, se basa en la ruta que termina inicialmente en un nombre de archivo. Si se desconoce si la ruta termina en un nombre de archivo o nombre de carpeta, entonces requiere que verifique la ruta real para ver si el archivo / carpeta existe primero en la ubicación. En ese caso, la respuesta de Dan Dimitru puede ser más apropiada.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-17 15:10:10
Prueba esto:
string filename = @"C:/folder1/folder2/file.txt";
string FolderName = new DirectoryInfo(System.IO.Path.GetDirectoryName(filename)).Name;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-18 11:16:58
Utilicé este fragmento de código para obtener el directorio de una ruta cuando no hay nombre de archivo en la ruta:
Por ejemplo "c:\tmp\test\visual";
string dir = @"c:\tmp\test\visual";
Console.WriteLine(dir.Replace(Path.GetDirectoryName(dir) + Path.DirectorySeparatorChar, ""));
Salida:
Visual
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-28 12:28:16
Simple y limpio. Solo usa System.IO.FileSystem
- funciona como un encanto:
string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-14 18:11:38
var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-11 14:54:43
DirectoryInfo hace el trabajo de eliminar el nombre del directorio
string my_path = @"C:\Windows\System32";
DirectoryInfo dir_info = new DirectoryInfo(my_path);
string directory = dir_info.Name; // System32
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-02 14:21:47
El siguiente código ayuda a obtener solo el nombre de la carpeta
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; } }
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-28 06:40:59
También es importante tener en cuenta que mientras se obtiene una lista de nombres de directorio en un bucle, la clase DirectoryInfo
se inicializa una vez, lo que permite solo la primera llamada. Para evitar esta limitación, asegúrese de usar variables dentro de su bucle para almacenar el nombre de cualquier directorio individual.
Por ejemplo, este código de ejemplo recorre una lista de directorios dentro de cualquier directorio padre mientras agrega cada nombre de directorio encontrado dentro de una Lista de cadenas tipo:
[C#]
string[] parentDirectory = Directory.GetDirectories("/yourpath");
List<string> directories = new List<string>();
foreach (var directory in directories)
{
// Notice I've created a DirectoryInfo variable.
DirectoryInfo dirInfo = new DirectoryInfo(directory);
// And likewise a name variable for storing the name.
// If this is not added, only the first directory will
// be captured in the loop; the rest won't.
string name = dirInfo.Name;
// Finally we add the directory name to our defined List.
directories.Add(name);
}
[VB.NET]
Dim parentDirectory() As String = Directory.GetDirectories("/yourpath")
Dim directories As New List(Of String)()
For Each directory In directories
' Notice I've created a DirectoryInfo variable.
Dim dirInfo As New DirectoryInfo(directory)
' And likewise a name variable for storing the name.
' If this is not added, only the first directory will
' be captured in the loop; the rest won't.
Dim name As String = dirInfo.Name
' Finally we add the directory name to our defined List.
directories.Add(name)
Next directory
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-25 06:58:16
Esto 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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-12 07:23:15
// 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
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-21 07:02:44