// Determine whether the file type meets the standard
Public static bool isallowedextension (fileupload hifile)
{
System. Io. filestream FS = new system. Io. filestream (hifile. postedfile. 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
{
}
R. Close ();
FS. Close ();
If (fileclass = "255216" | fileclass = "7173") // The 255216 is JPG, 7173 is GIF, 6677 is BMP, 13780 is PNG, and 7790 is exe, 8297 is RAR
{
Return true;
}
Else
{
Return false;
}
}
/** // <Summary>
/// Save the uploaded file
/// </Summary>
/// <Param name = "filetype"> file type to be verified </param>
/// <Param name = "lenghtkb"> size (unit: KB) </param>
/// <Param name = "filepath"> saved path (absolute path) </param>
/// <Param name = "Upload"> controls for uploading files </param>
/// <Param name = "FILENAME"> succeeded: the file name is saved. Failed: error message </param>
/// <Returns> whether the storage is successful </returns>
Public static bool SaveFile (string filetype, int lenghtkb, string filepath, fileupload upload, out string filename)
{
// Determine whether a file has been uploaded
If (! Upload. hasfile)
{
Filename = "invalid file content ";
Return false;
}
// Determine the file size
If (upload. postedfile. contentlength & gt; lenghtkb * 1024)
{
Filename = "the file size exceeds the upload size ";
Return false;
}
// File type
String type = upload. filename;
String last = type. substring (type. lastindexof ('.') + 1 );
Type = upload. postedfile. contenttype;
// Type = type. substring (type. lastindexof ('.') + 1 );
If (type. substring (0, 5 )! = Filetype)
{
Filename = "invalid file type ";
Return false;
}
Datetime date = datetime. now;
// Generate the file name
Filename = date. year. tostring () + date. Month. tostring () + date. Day. tostring () + date. Hour. tostring () +
Date. Minute. tostring () + date. Second. tostring () + getrandom (). Next (0,999) + "." + last;
Upload. saveas (filepath + @ "\" + filename );
Return true;
}