[英]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.