[英]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:\mydir
和C:\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\
将导致DirB
但C:\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 ![]() |
17.73 ns ![]() |
50.59 ns ![]() |
UseGetDirectoryName![]() |
621.2 ns ![]() |
18.26 ns ![]() |
53.56 ns ![]() |
UseGetDirectoryInfo![]() |
1,397.8 ns ![]() |
26.71 ns ![]() |
65.51 ns ![]() |
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()
返回完整路径而没有尾随\
这将返回错误的目录...即我从现在开始使用DirectoryInfo
或TrimEnd()
因为我不想犯同样的错误。
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 ![]() |
0.976 μs ![]() |
1.085 μs ![]() |
UseGetDirectoryName![]() |
49.30 μs ![]() |
0.703 μs ![]() |
0.624 μs ![]() |
UseNewDirectoryInfo![]() |
51.82 μs ![]() |
1.021 μs ![]() |
1.362 μs ![]() |
UseDirectoryInfoGetDirectories![]() |
49.78 μs ![]() |
0.789 μs ![]() |
0.877 μs ![]() |
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.