繁体   English   中英

C#剪切文件来自Path的名称

[英]C# cut file Name from Path

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

例如:

在此输入图像描述

我需要从路径中删除文件名(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”之间的名称..什么是确切的代码?

任何建议都会有所帮助

只需使用类Path和它的方法GetFileNameWithoutExtension

string file = Path.GetFileNameWithoutExtension(s);

警告:在此上下文中(只是没有扩展名且没有在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

等等。

这是一个小提琴

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM