如何find文件的扩展名?
在我的Web应用程序(asp.net,C#)我上传video文件的页面,但我只想上传FLVvideo。 我怎样才能限制我上传其他扩展video?
Path.GetExtension
string myFilePath = @"C:\MyFile.txt"; string ext = Path.GetExtension(myFilePath); // ext would be ".txt" 在服务器上,您可以检查MIMEtypes,查找FLV MIMEtypes在这里或谷歌。
你应该检查MIMEtypes是
 video/x-flv 
如果你在C#中使用FileUpload,你可以这样做
 FileUpload.PostedFile.ContentType == "video/x-flv" 
我不确定这是否是你想要的,但是:
 Directory.GetFiles(@"c:\mydir", "*.flv"); 
要么:
 Path.GetExtension(@"c:\test.flv") 
您可以简单地阅读文件的stream
 using (var target = new MemoryStream()) { postedFile.InputStream.CopyTo(target); var array = target.ToArray(); 
首先5/6索引会告诉你文件types。 在FLV的情况下
private static readonly byte [] FLV = {70,76,86,1,5};
 Just do - var isAllowed = array.Take(5).SequenceEqual(FLV); 
如果是,那么它的FLV。
要么
阅读文件的内容
 var contentArray = target.GetBuffer(); var content = Encoding.ASCII.GetString(contentArray); 
前两个/三个字母会告诉你文件types。 在FLV的情况下
“FLV | \ 0 \ 0 \ 0 \ 0 \ 0 \ 0 ……”
 Just do - content.StartsWith("FLV") 
您将无法限制用户在客户端上传的文件types[*]。 你只能在服务器端做到这一点。 如果用户上传不正确的文件,则只有在file upload后才能识别上传。 没有可靠和安全的方法来阻止用户上传任何他们想要的文件格式。
[*]是的,你可以做各种聪明的东西来检测文件扩展名,然后再开始上传,但不要依赖它。 有人会绕过它,迟早会上传他们喜欢的任何东西。
 另外,如果你有一个FileInfo fi ,你可以简单地做: 
 string ext = fi.Extension; 
 它将保存文件的扩展名(注意:它将包含. ,所以上面的结果可能是: .jpg .txt ,等等…. 
此解决scheme还有助于多个扩展名的情况下,如“Avishay.student.DB”
  FileInfo FileInf = new FileInfo(filePath); string strExtention = FileInf.Name.Replace(System.IO.Path.GetFileNameWithoutExtension(FileInf.Name), ""); 
以。。结束()
在DotNetPerls上find了一个我更喜欢的替代解决scheme,因为它不需要你指定一个path。 这是一个例子,我用一个自定义的方法来帮助我填充一个数组
  // This custom method takes a path // and adds all files and folder names to the 'files' array string[] files = Utilities.FileList("C:\", ""); // Then for each array item... foreach (string f in files) { // Here is the important line I used to ommit .DLL files: if (!f.EndsWith(".dll", StringComparison.Ordinal)) // then populated a listBox with the array contents myListBox.Items.Add(f); }