原始響應:
字符串轉換爲Uri
對象,你可以做到以下幾點:
//filePath = @"http://s.ion.com/abc/Std/isd/text.txt"
Uri uri = new Uri(filePath);
string output = uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length - 1); // -1 removes the '/' character at the end
// output = "http://s.ion.com/abc/Std/isd"
*注:Last()
功能是從System.Linq
庫。如果您不使用此庫,則仍可通過用uri.Segments[uri.Segments.Length - 1].Length
替換uri.Segments.Last().Length
來獲取最後一個段。
更新基於this comment響應:
//filePath = @"http://s.ion.com/abc/Std/isd/ser/wer/text.txt"
Uri uri = new Uri(filePath);
string output = uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.[uri.Segments.Length - 3].Length - 1);
// uri.Segments.Length - 3 removes the last 3 unrequired "segments"
// -1 removes the '/' character at the end
// output = "http://s.ion.com/abc/Std/isd"
根據最新修訂更新的響應:
//filePath = @"http://s.ion.com/abc/Std/isd/wer/we/wed/sa/ser/text.txt"
Uri uri = new Uri(filePath);
string output = uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.[uri.Segments.Length - 6].Length - 1);
// uri.Segments.Length - 6 removes the last 6 unrequired "segments"
// -1 removes the '/' character at the end
// output = "http://s.ion.com/abc/Std/isd"
如果這三個字符串是可能的,那麼你可以做一個條件語句來確定要操縱的字符串。
if (/* string 1 */)
// see original response
else if (/* string 2 */)
// see first updated response
else if (/* string 3 */)
// see second updated response
如果想,如果我有這樣的字符串文件路徑= @「http://s.ion.com/abc/Std/isd/ser/wer/text.txt路徑「;我怎麼能繼續得到相同的輸出? –
你的意思是,如果在字符串前沒有「http://」,你如何在它前面得到一個帶有「http://」的輸出?如果(!url.StartsWith(@「http://」)){url = @「http://」+ url; } –
你錯了。如果字符串是「http://s.ion.com/abc/Std/isd/ser/wer/text」,我需要輸出「http://s.ion.com/abc/Std/isd」。文本」; –