从路径获取文件夹名称

时间:2010-09-17 14:56:38

标签: c# path filesystems

string path = "C:/folder1/folder2/file.txt";

我可以使用哪些对象或方法会产生folder2的结果?

11 个答案:

答案 0 :(得分:292)

我可能会使用类似的东西:

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

GetDirectoryName的内部调用将返回完整路径,而对GetFileName()的外部调用将返回最后一个路径组件 - 这将是文件夹名称。

无论路径是否实际存在,此方法都有效。然而,这种方法依赖于最初以文件名结尾的路径。如果不知道路径是以文件名还是文件夹名结尾 - 那么它需要您检查实际路径以查看该位置是否存在文件/文件夹。在这种情况下,Dan Dimitru的回答可能更合适。

答案 1 :(得分:28)

试试这个:

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

答案 2 :(得分:11)

简单&清洁。只使用System.IO.FileSystem - 就像魅力一样:

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

答案 3 :(得分:6)

当路径中没有文件名时,我使用此代码段获取路径的目录:

例如“c:\ tmp \ test \ visual”;

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

输出:

  

视觉

答案 4 :(得分:6)

DirectoryInfo 执行剥离目录名称的作业

import sqlite3
import os
from shutil import copyfile

db = sqlite3.connect('example.db')
#prints a welcome message
print("WELCOME TO BlaBlah !!!")
print("We have three genre types avalible.\nPop\nHip Hop\nClassic\nWe also have five avalible artists.\nDean\nIsbean\nNoazy\nKepen\nDrip\n")
answer = input("Do you already have an account ?\nIf yes type 'y' if no type 'n'! ")#gets user input
loggedIn = False #sets boolean to false
if answer == "y": #uses the user input to see which step needs to be taken next
    cursor = db.cursor()
    username = input("Enter Your username ") #asks for user to input username
    password = input("Enter Your password ") #asks for user to input password
    cursor.execute('''SELECT username, password, address, birth, artist, genre FROM users''')
    for row in cursor: #makes a for loop that goes through the file until all rows are checked
        if row[0]==username: #checks if row[0] is equal to username
            if row[1]==password: #checks if row[1] is equal to password
                print("you are logged in") #if both rows match then it prints out a message
                loggedIn == True #sets boolean to true
                change = input("Your fav artist is "+row[4]+" and your fav genre is "+row[5]+".\nTo change something press '1' otherwise press any key ")
                playlist = input("To create a new playlist press '2' or to view a created playlist press '1' ")
                if change == "1":
                    newChange = input("To change fav artist type '1' To change fav genre type '2' ")
                    if newChange =="1":
                        newArtist = input("Enter new fav artist ")
                        cursor.execute('''UPDATE students SET artist = ? WHERE username = ?''',(newArtist ,username))
                        db.commit()
                    else:
                        newGenre = input("Enter new fav genre ")
                        cursor.execute('''UPDATE students SET genre = ? WHERE username = ?''',(newGenre ,username))
                        db.commit()
                elif playlist == '1':
                    print('View Created playlist')
                elif playlist == '2':
                    runit = input('To view a song library press "1" ')
                    if runit == '1':

                        #cursor.execute('''CREATE TABLE IF NOT EXISTS library(song_id INTEGER PRIMARY KEY, song TEXT, artist TEXT, genre TEXT, time INTEGER)''') 

                        cursor.execute('''SELECT song_id, song, artist, genre, time FROM library ORDER BY song ASC''')
                        for row in cursor:
                            song_id = row[0]
                            songName = row[1]
                            name = row[2]
                            age = row[3]
                            time = row[4]
                            print('--------Song record---------')
                            print('Song_id: ' +str(song_id))
                            print('Song Name: ' + str(songName))
                            print('Artist Name: ' + name)
                            print('Genre: ' + str(age))
                            print('Time: ' + str(time))
                            print('-------------------------------\n')

                        createPlaylist = input('to create a playlist press "1" ')
                        if createPlaylist == '1':
                            cursor.execute('''CREATE TABLE IF NOT EXISTS playlists(user_id INTEGER, playlist_id INTEGER PRIMARY KEY, song_id)''')
                        else:
                            print('####')
                else:
                    print('####')

答案 5 :(得分:2)

var fullPath = @"C:\folder1\folder2\file.txt";
var lastDirectory = Path.GetDirectoryName(fullPath).Split('\\').LastOrDefault();

答案 6 :(得分:1)

下面的代码有助于获取文件夹名称


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

答案 7 :(得分:0)

还要注意,在循环中获取目录名称列表时,DirectoryInfo类仅初始化一次,因此仅允许首次调用。为了绕过此限制,请确保在循环中使用变量来存储任何单个目录的名称。

例如,此示例代码循环遍历任何父目录中的目录列表,同时在字符串类型的列表中添加每个找到的目录名称:

[C#]

string[] parentDirectory = Directory.GetDirectories("/yourpath");
List<string> directories = new List<string>();

foreach (var directory in parentDirectory)
{
    // 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 parentDirectory

    ' 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

答案 8 :(得分:0)

string Folder = Directory.GetParent(path);

答案 9 :(得分:-1)

这很难看,但避免了分配:

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

答案 10 :(得分:-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
  }
}