简体   繁体   English

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

[英]C# cut file Name from Path

I am creating an Image Extraction tool and I am able to retrieve the Images with full path.. 我正在创建一个图像提取工具,我能够检索完整路径的图像..

For Example: 例如:

在此输入图像描述

I need to cut the File name (rss) from path... 我需要从路径中删除文件名(rss)...

I search posts and Tried following 我搜索帖子并尝试以下

//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)));

None seems to be working 似乎没有工作

I want the name between "images" and "png" ..What can be the exact code? 我想要“images”和“png”之间的名称..什么是确切的代码?

Any Suggestion will be helpful 任何建议都会有所帮助

Just use the class Path and its method GetFileNameWithoutExtension 只需使用类Path和它的方法GetFileNameWithoutExtension

string file = Path.GetFileNameWithoutExtension(s);

Warning: In this context (just the filename without extension and no arguments passed after the URL) the method works well, however this is not the case if you use other methods of the class like GetDirectoryName. 警告:在此上下文中(只是没有扩展名且没有在URL之后传递参数的文件名),该方法运行良好,但是如果您使用类的其他方法(如GetDirectoryName)则不是这种情况。 In that context the slashes are reversed into Windows-style backslashes "\\" and this could be an error for other parts of your program 在该上下文中,斜杠反转为Windows样式的反斜杠“\\”,这可能是程序其他部分的错误

Another solution, probably more WEB oriented is through the class Uri 另一种解决方案,可能更多面向WEB,是通过Uri类

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

but I find this a lot less intuitive and more error prone. 但我觉得这很不直观,更容易出错。

In your example you're using a uri so you should use System.Uri 在您的示例中,您使用的是uri,因此您应该使用System.Uri

System.Uri uri = new System.Uri(s);
string path = uri.AbsolutePath;
string pathWithoutFilename = System.IO.Path.GetDirectoryName(path);

Why use Uri ? 为什么要用Uri Because it will handle things like 因为它会处理类似的事情

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

Etc. 等等。

Here's a fiddle 这是一个小提琴

You should use the various System.IO.Path functions to manipulate paths as they work cross platform. 您应该使用各种System.IO.Path函数来操作跨平台工作的路径。 Similarly you should use the System.Uri class to manipulate Uris as it will handle all the various kinds of edge cases like escaped characters, fragments, query strings, etc. 类似地,您应该使用System.Uri类来操作Uris,因为它将处理所有各种边缘情况,如转义字符,片段,查询字符串等。

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

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