檢測真實的檔案型別函式

iDotNetSpace發表於2009-02-23

private bool IsAllowedExtension(HttpPostedFile hifile)
        {
            
bool ret = false;

            System.IO.FileStream fs 
= new System.IO.FileStream(hifile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader r 
= new System.IO.BinaryReader(fs);
            
string fileclass = "";
            
byte buffer;
            
try
            {
                buffer 
= r.ReadByte();
                fileclass 
= buffer.ToString();
                buffer 
= r.ReadByte();
                fileclass 
+= buffer.ToString();
            }
            
catch
            {
                
return false;
            }
            r.Close();
            fs.Close();
            
/*副檔名說明
             *7173        gif 
             *255216      jpg
             *13780       png
             *6677        bmp
             *239187      txt,aspx,asp,sql
             *208207      xls.doc.ppt
             *6063        xml
             *6033        htm,html
             *4742        js
             *8075        xlsx,zip,pptx,mmap,zip
             *8297        rar   
             *01          accdb,mdb
             *7790        exe,dll           
             *5666        psd 
             *255254      rdp 
             *10056       bt種子 
             *64101       bat 
             
*/


            String[] fileType 
= { "255216""7173""6677""13780""8297""5549""870""87111""8075" };

            
for (int i = 0; i < fileType.Length; i++)
            {
                
if (fileclass == fileType[i])
                {
                    ret 
= true;
                    
break;
                }
            }
            
return ret;       
        }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-557463/,如需轉載,請註明出處,否則將追究法律責任。

相關文章