C#从路径中剪切文件名

C#从路径中剪切文件名,c#,path,C#,Path,我正在创建一个图像提取工具,我能够检索完整路径的图像 例如: 我需要从路径中剪切文件名(rss) 我搜索了一些帖子,并试着跟踪 //1. //string str = s.Split('/', '.')[1]; //2. string s1; // string fileName = "abc.123.txt"; int fileExtPos = s.LastIndexOf(".");

我正在创建一个图像提取工具,我能够检索完整路径的图像

例如:

我需要从路径中剪切文件名(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)));
似乎没有一个起作用

我想知道“图片”和“png”之间的名称。确切的代码是什么

任何建议都会有帮助

只需使用该类及其方法即可

警告:在这种情况下(只有不带扩展名的文件名和URL后没有传递参数),该方法工作正常,但是如果使用该类的其他方法,如GetDirectoryName,则情况并非如此。在这种情况下,斜杠被反转为Windows样式的反斜杠“\”,这可能是程序其他部分的错误

另一种可能更面向WEB的解决方案是通过类Uri

Uri u = new Uri(s);
string file = u.Segments.Last().Split('.')[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
等等


当路径跨平台工作时,应该使用各种函数来操纵路径。类似地,您应该使用该类来操作URI,因为它将处理各种边缘情况,如转义字符、片段、查询字符串等。

right。,。但是稍微修改一下…(循环变量)string file=Path.GetFileNameWithoutExtension(s);对那些投了反对票的人说:你帮不了忙。如果有错误或不好的做法或其他什么。您可以帮助解释下一票。它显示/images/rss.png输出。很抱歉,我没有完成。现在试试看
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