从路径中截取文件名的C#代码

4
我正在创建一款图像提取工具,我能够检索到带有完整路径的图像。
例如: enter image description here 我需要从路径中截取文件名(rss)...
我查找了帖子并尝试了以下方法:
//1.
 //string str = s.Split('/', '.')[1];

//2.    
            string s1;

               // string fileName = "abc.123.txt";
                int fileExtPos = s.LastIndexOf(".");
                if (fileExtPos >= 0)
                    s1 = s.Substring(0, fileExtPos);


//3.
                //var filenames = String.Join(
                //    ", ",
                //    Directory.GetFiles(@"c:\", "*.txt")
                //       .Select(filename =>


//4.
                //           Path.GetFileNameWithoutExtension(filename)));

似乎都没有起作用

我想要"images"和"png"之间的名称..应该使用什么代码?

任何建议都会有帮助

2个回答

5
只需使用类Path及其方法GetFileNameWithoutExtension即可。
string file = Path.GetFileNameWithoutExtension(s);

警告:在这种情况下(仅使用文件名且URL后面没有参数),该方法可以正常工作,但如果您使用类似GetDirectoryName的其他类方法,则情况并非如此。在那种情况下,斜杠将被反转为Windows样式的反斜杠“\”,这可能会对程序的其他部分造成错误。

另一种解决方案,可能更适合WEB的是通过Uri类实现。

Uri u = new Uri(s);
string file = u.Segments.Last().Split('.')[0];

但我觉得这种方式不够直观且容易出错。


正确,但稍作修改...(在循环变量中)string file = Path.GetFileNameWithoutExtension(s); - Neeraj Verma
1
给那些点踩的人:你并没有帮助。如果有错误或不良实践等问题,你可以解释一下为什么要点踩。 - Steve

0
在你的例子中,你正在使用一个uri,所以你应该使用System.Uri
System.Uri uri = new System.Uri(s);
string path = uri.AbsolutePath;
string pathWithoutFilename = System.IO.Path.GetDirectoryName(path);

为什么要使用Uri?因为它可以处理像这样的事情

http://foo.com/bar/file.png#notthis.png
http://foo.com/bar/file.png?key=notthis.png
http://foo.com/bar/file.png#moo/notthis.png
http://foo.com/bar/file.png?key=moo/notthis.png
http://foo.com/bar/file%2epng

等等。

这里有一个小例子

你应该使用各种System.IO.Path函数来操作路径,因为它们可以跨平台工作。同样,你应该使用System.Uri类来操作Uri,因为它将处理所有各种边缘情况,如转义字符、片段、查询字符串等。


它显示 /images/rss.png 作为输出。 - vivek
抱歉我还没有完成。现在可以试一下。 - gman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接