2015-04-17 67 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());

相关问题