簡體   English   中英

從C#中的字符串中提取文件路徑或文件名

[英]Extract a file path or file name from a string in C#

以下字符串作為輸入:

var input = @"The file is: ""c:\sampleDirectory\sample subdirectory\sampleFileName.txt\"" which is a text file";

如何從上面的字符串中僅提取文件路徑。
優選使用Regex或類似方法。

編輯:

它可以使用LastIndexOf完成,由eocron回答。

但這是一個正則表達式的解決方案:

Match match = Regex.Match(input, @"""(.*)\\(.*\..*)[\\]?""", RegexOptions.IgnoreCase);

if (match.Success)
{   
    string path = match.Groups[1].Value;
    string filename = match.Groups[2].value;
}

如果您的輸入模式看起來與此完全相同,則可以在沒有Regex的情況下輕松完成:

var magic1 = 14;//index of first quotation mark
var magic2 = 22;//suffix index of last quotation mark
var result = str.Substring(magic, str.Lenght-magic2-magic1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM