Asp.net string.split()(1)删除第一个字符

Asp.net string.split()(1)删除第一个字符,asp.net,string,vb.net,split,Asp.net,String,Vb.net,Split,当我在“_Pub”上拆分一个字符串并获取该字符串的后半部分时,我遇到了一个问题。它删除了第一个字符,我不明白为什么或如何修复它,除非我将该字符添加回 strFilePath = "/C:/Dev/Edge/_Publications/Ann Report/2013-2016/2016 Edge.pdf" Dim relPath = strFilepath.Split("_Publications")(1) lb.CommandArgument = relPath 返回Publicati

当我在“_Pub”上拆分一个字符串并获取该字符串的后半部分时,我遇到了一个问题。它删除了第一个字符,我不明白为什么或如何修复它,除非我将该字符添加回

 strFilePath = "/C:/Dev/Edge/_Publications/Ann Report/2013-2016/2016 Edge.pdf"

 Dim relPath = strFilepath.Split("_Publications")(1)
 lb.CommandArgument = relPath

返回Publications\Ann Report\2013-2016\2016 Edge.pdf

函数应该从结果中排除整个分隔符。能否重新检查并确认输入和输出字符串?

作为分隔符的不是字符串数组“string()”,而是常规字符串。您需要一个字符串数组来使用字符串作为分隔符。否则它将使用字符串的第一个字符

试试这个

Dim relPath = strFilepath.Split(new string() {"_Publications"}, StringSplitOptions.RemoveEmptyEntries)(1)

似乎您希望获取路径中从某个目录开始的部分。拆分路径可能不是一个好主意:想象一下,如果目录“C:\Dev\Edge\\u Publications”中有一个文件“My\u Publications\u 2017.pdf”。按照您在问题中的意图进行拆分,将得到字符串数组{“C:\Dev\Edge\”、“\My”、“_2017.pdf”}。正如其他地方指出的那样,您使用的String.Split无论如何都不会这样做

更可靠的方法是找到起始目录的名称在完整路径中的位置,并获取以其开头的路径的子字符串,例如:

Function GetRelativePath(fullPath As String, startingDirectory As String) As String
    ' Fix some errors in how the fullPath might be supplied:
    Dim tidiedPath = Path.GetFullPath(fullPath.TrimStart("/".ToCharArray()))

    Dim sep = Path.DirectorySeparatorChar
    Dim pathRoot = sep & startingDirectory.Trim(New Char() {sep}) & sep
    Dim i = tidiedPath.IndexOf(pathRoot)

    If i < 0 Then
        Throw New DirectoryNotFoundException($"Cannot find {pathRoot} in {fullPath}.")
    End If

    ' There will be a DirectorySeparatorChar at the start - do not include it
    Return tidiedPath.Substring(i + 1)

End Function
产出:

_出版物\Ann报告\2013-2016\2016 Edge.pdf
Ann报告\2013-2016\2016 Edge.pdf


我猜测您可能有多个格式错误的路径,以“/”开头,并使用“/”作为目录分隔符而不是“\”,因此我加入了一些代码来缓解这些问题。

请显示确切的输入和输出,如果您这样做的话(
(strFilepath.Split(“\u Publications”))(1)
?尝试了这一点,并得到了相同的输出可能重复,因为大多数人在使用分隔符时,不希望所有数据在开头或结尾都被它污染。因此,当您拆分时,可以在字符串/字符的任意一侧(或分隔符之间)获取数据,但不能获取分隔符本身。@AndrewMorton我知道。我很懒;)抢手货这一点很容易被忽略。@chillzy是正确的-整个分隔符被删除,但为函数提供一个字符串意味着它被视为一个字符分隔符数组。
Dim s = "/C:/Dev/Edge/_Publications/Ann Report/2013-2016/2016 Edge.pdf"
Console.WriteLine(GetRelativePath(s, "_Publications"))
Console.WriteLine(GetRelativePath(s, "\Ann Report"))