Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#如何从子字符串中获取一个值_C#_Substring - Fatal编程技术网

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

c#如何从子字符串中获取一个值,c#,substring,C#,Substring,如何解决这个问题 我想改变的是: C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\ 到新值: value=“1.0.11” 您只需获得相应的 是伟大的,但作为一种选择 string s = @"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\"; string[] array = s.Split('\\'

如何解决这个问题

我想改变的是:

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

到新值:

value=“1.0.11”

您只需获得相应的

是伟大的,但作为一种选择

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]);
输出将是

1.0.1.1
这里有一种替代方法:

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
这基本上删除了最后一个目录,然后将最后一个目录视为文件名,因此返回最后一个目录


根据以下@JeppeStigNielsen的评论,这里有一个更好的、独立于平台的替代方案

var value = Path.GetFileName(Path.GetDirectoryName(path));
如果同时存在文件名,则此操作也会起作用

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

好的,请阅读有关.Net字符串类的文档。非常强大。然后,试着有明确的需求,那么,为什么不实际编写一些东西呢?@Kek,为什么要阅读
string
类的文档?我宁愿阅读我的答案中所示的
DirectoryInfo
类的文档。。。你猜@user1358072想要提取目录。。。恭喜你,我无法推断:我有这个,我想要那个。。。那么,这是什么?当你可以检查
数组的长度时,为什么要用Linq使用
.Count
?@JeppeStigNielsen是的,你是对的。那是毫无意义的。更新。请注意,这需要对指定目录的读取权限,在大多数情况下都不会有问题。这真的会导致磁盘操作,还是只是进行字符串操作?显然,对于像
newdirectoryinfo(path.Exists)这样的东西,它必须执行I/O操作。当然,使用框架的实用程序来处理文件路径而不是临时字符串操作的原理是非常合理的。除非有人能够保证上述使用
DirectoryInfo
不会导致权限检查或磁盘读取,否则我将使用
Path
类的解决方案,正如Eren Ersönmez的回答。是的,这将导致I/O权限检查。我尝试了
Path.GetFileName(Path.GetDirectoryName(Path))
,它似乎也能工作。@JeppeStigNielsen那更好,因为即使存在文件名,它也能工作。在您的版本中,可以更改
new[]{'/','\\}
进入
Path.altdirectoryseportorchar,Path.directoryseportorchar
。请注意,
TrimEnd
方法在其参数上有
params
modifyer,因此数组创建语法是多余的。@JeppeStigNielsen也为true。
var value = Path.GetFileName(Path.GetDirectoryName(".../1.0.1.1/somefile.etc"));
// returns 1.0.1.1