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

我可以使用什么对象或方法来给我结果文件夹2?


当前回答

试试这个:

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

其他回答

下面的代码只帮助获取文件夹名称


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

另一种方法是分割路径,使用c# 8.0中引入的Index Struct从路径中获取倒数第二个元素。

var path = @"C:\folder1\folder2\file.txt";
var folder = path.Split(@"\")[^2]; // 2nd element from the end

Console.WriteLine(folder); // folder2

DirectoryInfo执行剥离目录名的工作

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

试试这个:

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

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

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