简体   繁体   English

C#如何从子字符串中获取一个值

[英]c# how to get one value from substring

How to solve this? 如何解决呢?

What i want to change this : 我想改变这个:

C:\\files\\team\\business\\dev\\Source\\systems\\extension\\destination\\1.0.1.1\\ C:\\ files \\ team \\ business \\ dev \\ Source \\ systems \\ extension \\ Destination \\ 1.0.1.1 \\

to new value: 达到新的价值:

value = "1.0.11"; 值=“ 1.0.11”;

You could just get the Name of the corresponding DirectoryInfo : 您只需获取相应DirectoryInfoName

string path = @"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
string version = new DirectoryInfo(path).Name;

Alternative method: 替代方法:

var path = @"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
var value = Path.GetFileName(path.TrimEnd(new[]{'/','\\'}));
// OUTPUT: 1.0.1.1

This basically removes any last directory delimeters and then treats the last directory as a filename, so it returns the last directory. 这基本上删除了最后一个目录分隔符,然后将最后一个目录视为文件名,因此它返回了最后一个目录。


Based on @JeppeStigNielsen 's comments below, here's a better, platform independent alternative. 根据下面的@JeppeStigNielsen的评论,这是一个更好的,独立于平台的替代方案。

var value = Path.GetFileName(Path.GetDirectoryName(path));

This will work if there is a file name present as well. 如果还存在文件名,这将起作用。

var value = Path.GetFileName(Path.GetDirectoryName(".../1.0.1.1/somefile.etc"));
// returns 1.0.1.1

Darin's answer is great but as an alternative; 达林的答案很好,但可以选择。

string s = @"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";

string[] array = s.Split('\\');
Console.WriteLine(array[array.Length - 2]);

Output will be; 输出将是;

1.0.1.1

Here a DEMO . 这里是演示

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

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