简体   繁体   中英

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\\

to new value:

value = "1.0.11";

You could just get the Name of the corresponding DirectoryInfo :

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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