简体   繁体   English

C# 获取目录名称

[英]C# Get Directory Names

Here is some code i have been trying to use to get just directory names - However its returning the full filepath rather than all the directories in SUBDIR2.这是我一直试图用来获取目录名称的一些代码 - 但是它返回完整的文件路径而不是 SUBDIR2 中的所有目录。 I can do a split string but the length of the Dir changes我可以做一个拆分字符串,但 Dir 的长度会发生变化

public void Getdire1(string Servername)
{
    string[] dirs = Directory.GetDirectories("\\\\" 
        + Servername 
        + "\\E$\\SUBDIR1\\SUBDIR2\\");

    foreach (string item in dirs)
    {
        MessageBox.Show(item);
    }
}

Can anyone help please任何人都可以帮忙吗

Use Path.GetDirectoryName(string)使用Path.GetDirectoryName(string)

https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname?view=net-5.0 https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getdirectoryname?view=net-5.0

public void Getdire1(string Servername) 
{
    string[] dirs = Directory.GetDirectories("\\\\" + Servername + "\\E$\\SUBDIR1\\SUBDIR2\\");
    

    foreach (string item in dirs)
    {
        MessageBox.Show(Path.GetDirectoryName(item));
    }
}

See the samples in the docs to make sure you get the desired output, be for example mindful about C:\mydir and C:\mydir\ .请参阅文档中的示例以确保获得所需的 output,例如注意C:\mydirC:\mydir\

EDIT: :编辑::

In that case you can use Path.GetFileName(string) but this only works if your path does not end with \ , eg C:\MyDir works but C:\MyDir\ won't.在这种情况下,您可以使用Path.GetFileName(string)但这仅在您的路径不以\结尾时才有效,例如C:\MyDir有效,但C:\MyDir\不会。

You can use String.TrimEnd(string) for this like so: "C:\\mydir\\".TrimEnd('\\') .您可以像这样使用String.TrimEnd(string)"C:\\mydir\\".TrimEnd('\\') I think Path.GetFileName("C:\\mydir\\".TrimEnd(Path.DirectorySeparatorChar)) would work.我认为Path.GetFileName("C:\\mydir\\".TrimEnd(Path.DirectorySeparatorChar))会起作用。

Or even this: Path.GetFileName(Path.GetDirectoryName("C:\\mydir\\")) but be careful, C:\DirA\DirB\ will result in DirB but C:\DirA\DirB will result in DirA !甚至这样: Path.GetFileName(Path.GetDirectoryName("C:\\mydir\\"))但要小心, C:\DirA\DirB\将导致DirBC:\DirA\DirB将导致DirA

EDIT2: The answer from @Stefano Cavion also seems sensible, although if I just wanted the name I personally would not like to instantiate a whole class just to get the name of a directory from some string. EDIT2: @Stefano Cavion 的答案似乎也很明智,尽管如果我只是想要这个名字,我个人不想实例化整个 class 只是为了从某个字符串中获取目录的名称。 Thats just taste.那只是味道。 For funsies i've decided to run a small benchmark to see if there are better choices performance wise, and funnily enough the .TrimEnd() solution seems to be the fastest in a way.对于有趣的人,我决定运行一个小型基准测试,看看是否有更好的选择性能明智,而且有趣的是.TrimEnd()解决方案似乎在某种程度上是最快的。 Of course caring about performance on this level seems a bit too much unless you're doing something very special so take this with a grain of salt...当然,除非您正在做一些非常特别的事情,否则在此级别上关心性能似乎有点过分了,所以对此持保留态度...

BenchmarkDotNet=v0.13.0, OS=Windows 10.0.17134.677 (1803/April2018Update/Redstone4)
Intel Core i7-7700HQ CPU 2.80GHz (Kaby Lake), 2 CPU, 7 logical and 7 physical cores
.NET SDK=5.0.202
  [Host]     : .NET Core 3.1.14 (CoreCLR 4.700.21.16201, CoreFX 4.700.21.16208), X64 RyuJIT  [AttachedDebugger]
  DefaultJob : .NET Core 3.1.14 (CoreCLR 4.700.21.16201, CoreFX 4.700.21.16208), X64 RyuJIT
Method方法 Mean意思是 Error错误 StdDev标准差
UseTrimEnd使用修剪结束 462.2 ns 462.2 纳秒 17.73 ns 17.73 纳秒 50.59 ns 50.59 纳秒
UseGetDirectoryName使用GetDirectoryName 621.2 ns 621.2 纳秒 18.26 ns 18.26 纳秒 53.56 ns 53.56 纳秒
UseGetDirectoryInfo使用GetDirectoryInfo 1,397.8 ns 1,397.8 纳秒 26.71 ns 26.71 纳秒 65.51 ns 65.51 纳秒

The environment and .net core version would also give some variance, as well as me using the computer whilst the test was running.环境和 .net 核心版本也会产生一些差异,以及我在测试运行时使用计算机。

Code:代码:

public class PathBenchMark
{
    public List<string> Paths = new List<string>(new[] { @"C:\MyDir", @"C:\MyDir\", @"C:\A\B", @"C:\A\B\" });

    [Benchmark]
    public List<string> UseTrimEnd() => Paths.Select(c => Path.GetFileName(c.TrimEnd(Path.DirectorySeparatorChar))).ToList();
    [Benchmark]
    public List<string> UseGetDirectoryName() => Paths.Select(c => Path.GetFileName(Path.GetDirectoryName(c))).ToList();
    [Benchmark]
    public List<string> UseGetDirectoryInfo() => Paths.Select(c => new DirectoryInfo(c).Name).ToList();

}

class Program
{
    public static void Main()
    {
        BenchmarkRunner.Run<PathBenchMark>();
    }
}

EDIT3: I've ran another benchmark by using new DirectoryInfo(string).GetDirectories(string) . EDIT3:我使用new DirectoryInfo(string).GetDirectories(string)运行了另一个基准测试。 I also edited the UseGetDirectoryName case, because Directory.GetDirectories() returns the full path without trailing \ which would return the wrong directory... Ie i'm going with DirectoryInfo or with TrimEnd() from now on since i don't wanna be making the same mistake.我还编辑了UseGetDirectoryName案例,因为Directory.GetDirectories()返回完整路径而没有尾随\这将返回错误的目录...即我从现在开始使用DirectoryInfoTrimEnd()因为我不想犯同样的错误。


BenchmarkDotNet=v0.13.0, OS=Windows 10.0.17134.677 (1803/April2018Update/Redstone4)
Intel Core i7-7700HQ CPU 2.80GHz (Kaby Lake), 2 CPU, 7 logical and 7 physical cores
.NET SDK=5.0.202
  [Host]     : .NET Core 3.1.14 (CoreCLR 4.700.21.16201, CoreFX 4.700.21.16208), X64 RyuJIT
  DefaultJob : .NET Core 3.1.14 (CoreCLR 4.700.21.16201, CoreFX 4.700.21.16208), X64 RyuJIT


Method方法 Mean意思是 Error错误 StdDev标准差
UseTrimEnd使用修剪结束 49.57 μs 49.57 微秒 0.976 μs 0.976 微秒 1.085 μs 1.085 微秒
UseGetDirectoryName使用GetDirectoryName 49.30 μs 49.30 微秒 0.703 μs 0.703 微秒 0.624 μs 0.624 微秒
UseNewDirectoryInfo使用新目录信息 51.82 μs 51.82 微秒 1.021 μs 1.021 微秒 1.362 μs 1.362 微秒
UseDirectoryInfoGetDirectories使用DirectoryInfoGetDirectories 49.78 μs 49.78 微秒 0.789 μs 0.789 微秒 0.877 μs 0.877 微秒
public class PathBenchMark
{
    private const string RootPath = @"C:\Program Files\dotnet\";
    public List<string> Paths => Directory.GetDirectories(RootPath, "*", SearchOption.AllDirectories).ToList();

    [Benchmark]
    public List<string> UseTrimEnd() => Paths.Select(c => Path.GetFileName(c.TrimEnd(Path.DirectorySeparatorChar))).ToList();
    
    [Benchmark]
    public List<string> UseGetDirectoryName() => Paths.Select(c => Path.EndsInDirectorySeparator(c) ? Path.GetFileName(Path.GetDirectoryName(c)) : Path.GetFileName(c) ).ToList();
    [Benchmark]
    public List<string> UseNewDirectoryInfo() => Paths.Select(c => new DirectoryInfo(c).Name).ToList();

    [Benchmark]
    public List<string> UseDirectoryInfoGetDirectories() => new DirectoryInfo(RootPath).GetDirectories("*", SearchOption.AllDirectories).Select(c => c.Name).ToList();
    
}

class Program
{
    public static void Main()
    {        
        BenchmarkRunner.Run<PathBenchMark>();
    }
}

You can use the DirectoryInfo class for retreive all the info you need, take a look to Microsoft documentation您可以使用DirectoryInfo class 来检索您需要的所有信息,请查看Microsoft 文档

        string[] dirs = Directory.GetDirectories("\\\\" + Servername + "\\E$\\SUBDIR1\\SUBDIR2\\");
        foreach(var dir in dirs)
        {
            var dirInfo = new DirectoryInfo(dir);
            MessageBox.Show(dinfo.Name);     //This will show only the directory name
            MessageBox.Show(dinfo.FullName); //This will show the complete path of the directory
        }

this should work for you.这应该适合你。

    public void Getdire1(string Servername)
    {
        string[] dirs = Directory.GetDirectories("\\\\" + Servername + "\\E$\\SUBDIR1\\SUBDIR2\\");
    
    
        foreach (string item in dirs)
        {
            System.Windows.Forms.MessageBox.Show(Path.GetFileName(item));
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM