2015-04-17 68 views
0

在我的C#應用​​程序中,我使用的是Path.GetExtension()如果文件名具有無效字符,GetExtension()將失敗

對此的輸入取決於文件處理。有時我的文件名可能有myfile-<ID>。我將在稍後階段處理ID值,因此我無法在檢查擴展時刪除<>

GetExtension()拋出無效字符的異常。當filename可能包含無效字符時,檢查文件是否具有擴展名的最佳方法是什麼?

+0

您的文件名可以包含「。」 ? –

+0

是的,它可以包含「。」 – user987316

+0

如果你知道你有什麼文件擴展名可以在點上分割它,並檢查最後的外觀是否有效。 –

回答

0

這會給你和。擴展名,如GetExtension做

Dim sPath,sExt As String 
sPath = "c:\namename<2>.RAR" 
If sPath.LastIndexOf(CChar(".")) <> -1 
    sExt = sPath.Substring(sPath.LastIndexOf(CChar("."))) 
Else 
    sExt = Nothing 'no extension? 
End if 

對不起,你自找的C#

string sPath = null; 
string sExt = null; 
sPath = "c:\\namename<2>.RAR"; 
if (sPath.LastIndexOf(Convert.ToChar(".")) != -1) { 
    sExt = sPath.Substring(sPath.LastIndexOf('.'))); 
} else { 
    sExt = null; //no extension? 
} 

編輯: 如果有S IN路徑

「」
string sPath = null; 
string sExt = null; 
sPath = "c:\\folder.folder\folder\namename<2>.RAR"; 

sPath = sPath.Substring(sPath.LastIndexOf('\'))); 

if (sPath.LastIndexOf('.') != -1) { 
    sExt = sPath.Substring(sPath.LastIndexOf('.')); 
} else { 
    sExt = null; //no extension? 
} 
+1

1)如果文件名不包含「。」,但路徑確實會返回不正確的結果。 2)爲什麼'Convert.ToChar'而不是''.''? – CodesInChaos

+0

@CodesInChaos,編輯1)那麼,你可以檢查最後的'\'。 2)好吧,Vb傢伙的特殊習慣遷移到C#:) – Caveman

0

在尋找擴展名使用GetExtension(路徑)方法,而不是按原樣使用路徑,可以使用它清理。

下面是一個擴展方法吧:

using System.IO; 
using System.Linq; 

public static class FileNameExtensions 
{ 
    public static string ToValidPath(this string path) 
    { 
     return Path.GetInvalidFileNameChars() 
      .Aggregate(path, (previous, current) => previous.Replace(current.ToString(), string.Empty)); 
    } 
} 

所以,你現在可以調用與下面的參數GetExtension方法:GetExtension(path.ToValidPath());

相關問題