SoFunction
Updated on 2025-03-06

C# method to detect the true type of uploaded files

This article describes the method of C# to detect the true type of uploading files. Share it for your reference. The specific analysis is as follows:

If the file uploaded by the user is judged only based on the extension, it is easy to upload the executable file, which is very dangerous. This code can detect the real type of uploaded file on the server side.

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http:///TR/xhtml1/DTD/">
<script runat="server">
 void Alert(string s)
 {
  ((), "js", "alert('" + s + "')", true);
 }
 protected void Button1_Click(object sender, EventArgs e)
 {
  saveFile();
 }
 protected String saveFile()
 {
  String MaxSize = "1024";
  //Maximum file size  int imgMaxSize = Convert.ToInt32(MaxSize) * 1024 * 1024;
  HttpPostedFile imgFile = ;
  if (imgFile == null ||  == "")
  {
   Alert("Please select a file.");
   return "";
  }
  String dirPath = ("~/");
  string saveUrl = ("~/");
  if (!(dirPath))
  {
   Alert("The upload directory does not exist.");
   return "";
  }
  String fileName = ;
  String fileExt = (fileName).ToLower();
  if ( == null ||  > imgMaxSize)
  {
   Alert("The upload file size exceeds the limit.");
   return "";
  }
  //Verify file format  String fpath = IsAllowedExtension(imgFile);
  if ("" == fpath)
  {
   Alert("The picture format is incorrect.");
   return "";
  }
  String ymd = ("yyyyMMdd", );
  dirPath += ymd + "/";
  saveUrl = saveUrl + ymd + "/";
  //Judge whether the directory exists  if (!(dirPath))
  {
   //Create a directory   (dirPath);
  }
  String newFileName = ().ToString() + fileExt;
  //Picture name  String filePath = dirPath + newFileName;
  (fpath, filePath);
  String fileUrl = saveUrl + newFileName;
   = fileUrl;
  //ImageUrl = saveUrl + newFileName;
  return fileUrl;
 }
 public String IsAllowedExtension(HttpPostedFile f)
 {
  String newFile = ("~/" + ().ToString("D") + ".tmp");
  (newFile);
   fs = new (newFile, , );
   r = new (fs);
  string fileclass = "";
  byte buffer;
  buffer = ();
  fileclass = ();
  buffer = ();
  fileclass += ();
  ();
  ();
  /* File extension description
   *7173 gif
   *255216 jpg
   *13780 png
   *6677 bmp
    */
  Dictionary<String, String> ftype = new Dictionary<string, string>();
  //Add allowed file types  ("7173", "gif");
  ("255216", "jpg");
  ("13780", "png");
  ("6677", "bmp");
  if ((fileclass))
  {
   return newFile;
  }
  else
  {
   (newFile);
   return "";
  }
 }
</script>
<html xmlns="http:///1999/xhtml">
<head  runat="server">
</head>
<body>
 <form  runat="server">
 <asp:FileUpload ID="FuImg" runat="server" />
 <asp:Button ID="Button1" runat="server" 
 OnClick="Button1_Click" Text="Upload test" />
 <asp:Image ID="Img" runat="server" />
 </form>
</body>
</html>

I hope this article will be helpful to everyone's C# programming.