简体   繁体   English

从C#中的字符串中提取文件路径或文件名

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

Take following string as an input: 以下字符串作为输入:

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

How can I extract only the file path from the above string. 如何从上面的字符串中仅提取文件路径。
Using Regex or a similar approach is preferred. 优选使用Regex或类似方法。

Edited: 编辑:

It can be done with LastIndexOf as answered by eocron. 它可以使用LastIndexOf完成,由eocron回答。

But here is a regex solution : 但这是一个正则表达式的解决方案:

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

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

If your input patterns looks exactly like this, you could easily do this without Regex: 如果您的输入模式看起来与此完全相同,则可以在没有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