Upload the download file instance code in ASP.

Source: Internet
Author: User

Using System.IO;
Check that the upload file is not empty

if (file1.postedfile!=null)   {         string nam = File1.PostedFile.FileName;    Get the last "." In the file name (enclosing path). The index    int i= nam. LastIndexOf (".");    Gets the file name extension    string Newext =nam. Substring (i);    Here I automatically name the file according to the date and file size, make sure the file name does not repeat    DateTime now = DateTime.Now;     String Newname=now. Dayofyear.tostring () +file1.postedfile.contentlength.tostring ();     Save the file to the directory you want, which is the upload directory under the IIS root directory. You can change.    Note: I use Server.MapPath () to take the absolute directory of the current file. in ASP. "" Must replace    File1.PostedFile.SaveAs (Server.MapPath ("Upload" + Newname+newext));    This. Hyperlink1.navigateurl  = "Upload" +newname+newext;    Get the relevant properties for this file: file name, file type, file size    //fname. Text=file1.postedfile.filename;    Fenc. Text=file1.postedfile.contenttype;    Fsize. Text=file1.postedfile.contentlength.tostring ();   }

uploads can be used in the. NET HTML control of the file field of the upload control Ah, you drag onto the form, you can right-click as a server-side control to use, so write the code you want to upload a few lines, download directly connected to the file you want to download can be downloaded upload the file to the server, the direct link is downloaded. The class that is used to upload files:
Description: Directly in the CS file can be used to copy and paste. Using System;
using System.IO;

Using System.web.ui.htmlcontrols;namespace Youjian {//<summary>///upfile Summary description.  </summary> public class Upfile {public Upfile () {} #region allow the extension to be uploaded isallowedextension///<summary> Allow the extension to upload///</summary>///<paramname = "Hifile" >htmlinputfile controls </param>///<returns>  Returns true if allowed, otherwise false</returns> public bool Isallowedextension (HtmlInputFile hifile) {string Stroldfilepath = "" is returned; String strextension = ""; Allow upload extension, can be changed to read from the configuration file String[]arrextension = {". gif", ". jpg", ". jpeg", ". bmp", ". png"}; if (hifile. Postedfile.filename! = string. Empty) {Stroldfilepath = Hifile.  Postedfile.filename;  Get the file extension strextension = stroldfilepath.substring (Stroldfilepath.lastindexof ("."));  Determine if the extension is valid for (int i = 0;i<arrextension.length;i++) {if (Strextension.equals (Arrextension[i])) {return    True }}} return false; #endregion #region Determine if the upload file size exceeds the maximum isallowedlength//<summary>///Determine if the upload file is larger than the maximum value///</summary>//<param name= "Hifile" >htmlinputfile controls </param>//<returns> exceeds the maximum value to return false, Otherwise returns the maximum value of true.</returns> public bool Isallowedlength (HtmlInputFile hifile) {//Allow upload file size, which can be saved in an XML file in kilobytes int i = 2  0;  Returns true if the size of the uploaded file exceeds the maximum value and returns flase. if (hifile.  Postedfile.contentlength > I * 1024x768) {return false; } return true; #endregion #region Get a file name that does not duplicate getuniquestring///<summary>///Get a file name that is not duplicated///</summary>//<returns& Gt;</returns> public String getuniquestring () {//Gets the file name such as: 20050922101010 return DateTime.Now.ToString (" Yyyymmddhhmmss "); #endregion #region Delete the specified file DeleteFile///<summary>////</summary>//<param name= "Strabsolutep Ath "> File absolute path </param>//<param name=" strFileName "> file name </param> public void DeleteFile (string Strabsolutepath, String strFileName) {//To determine if the path has the last/symbol, no then automatically add if (Strabsolutepath.lastindexof ("//") = = Strabsolutepath.length) {//Determine if the file to be deleted exists if (FilE.exists (Strabsolutepath + strFileName)) {//delete file File.delete (Strabsolutepath + strFileName); }} else {if (file.exists (Strabsolutepath + "//" + strFileName)) {File.delete (Strabsolutepath + "//" + Strfilen   AME); }}} #endregion #region upload file and return filename SaveFile//<summary>///upload file and return filename///</summary>//<param name= "h IFile ">htmlinputfile control </param>///<param Name=" Strabsolutepath "> absolute path. such as: Server.MapPath (@" image/ Upload ") and Server.MapPath (@" image/upload/") are available, with/symbol also </param>///<returns> The returned file name is the file name after uploading </returns > public string SaveFile (HtmlInputFile hifile,string strabsolutepath) {string stroldfilepath = "", strextension = "", s Trnewfilename = ""; If the file name for the upload is not empty if (hifile. Postedfile.filename! = string. Empty) {Stroldfilepath = Hifile.   Postedfile.filename;   Get the file extension strextension = stroldfilepath.substring (Stroldfilepath.lastindexof ("."));   File after uploading the name strnewfilename = getuniquestring () + strextension; If the end of the path is/symbol, then upload the file directly if (Strabsolutepath.lastindexof ("//") = = Strabsolutepath.length) {hifile.   Postedfile.saveas (Strabsolutepath + strnewfilename); } else {Hifile.   Postedfile.saveas (Strabsolutepath + "//" + strnewfilename); }} return strnewfilename; #endregion #region re-upload the file, delete the original file Coverfile///<summary>///re-upload the file, delete the original file///</summary>//<param name= "Fffile" >htmlinputfile control </param>///<param Name= "Strabsolutepath" > absolute path. such as: Server.MapPath (@ "image/ Upload ") and Server.MapPath (@" image/upload/") are available, with/symbol also </param>///<param Name=" Stroldfilename "> old file name </ param> public void Coverfile (HtmlInputFile fffile,string strabsolutepath,string stroldfilename) {//Get new file name string str NewFileName = Getuniquestring (); if (ffFile.PostedFile.FileName! = string. Empty) {//Old picture is not empty first delete old picture if (stroldfilename! = string.   Empty) {DeleteFile (strabsolutepath,stroldfilename);  } SaveFile (Fffile,strabsolutepath); }} #endregion

C#.net file operation: Upload download delete file list

1. File Upload
----------
The following points:
HTML section:

<form id= "Form1" runat= "Server" method= "POST" enctype= "Multipart/form-data" > <input id= "FileUpLoad" type= " File "runat=" server/><br/> Background CS Partial button event//string Strfilefullname = System.IO.Path.GetFileName (this. FileUpLoad.PostedFile.FileName); This. FileUpLoad.PostedFile.SaveAs (Server.MapPath ("./xmlzip/") + Strfilefullname);

2. File download
----------

The SelectedIndexChanged event setting for the listbox related download connection protected void Lst_downloadfilelist_selectedindexchanged (object sender, EventArgs e) {  try  {   string strjs = "window.open (' xmlzip/";   Strjs + = This.lst_DownLoadFileList.SelectedItem.Text.Trim ();   Strjs + = "'); return false; ";   THIS.IMGBTN_DOWNLOADFILE.ATTRIBUTES.ADD ("onclick", Strjs);  }  catch (Exception ex)  {   ex. ToString ();  } }

Or you can change the text value of the label to achieve a click after the file download super connection

This. Label1.Text = "<a href=/" xmlzip/a.rar/">a.rar</a>"

3. File deletion
---------

String strFilePath = Server.MapPath (".. /countryflowmgr/xmlzip/"+this.lst_downloadfilelist.selecteditem.text.trim ()); if (file.exists (strFilePath)) {  file.delete (strFilePath);  if (file.exists (strFilePath))  {   Response.Write ("OK");  }  else  {   Response.Write ("OK");}  }

4. Get a list of files under the folder
-----------
#region get a list of currently available files
<summary>
Get a list of currently available files
</summary>
<param name= "Isalert" > Whether you need to pop up the message </param>

private void Fn_getcurrfilelist (bool Isalert) {try {//Find Xmlzip folder subordinate to itself Unitcodi Ng of the relevant zip file string strxmlzipdirectory = Server.MapPath (".   /xmlzip/");    if (directory.exists (strxmlzipdirectory)) {//directoryinfo di = new DirectoryInfo (environment.currentdirectory);   DirectoryInfo di = new DirectoryInfo (strxmlzipdirectory); fileinfo[] FI = di. GetFiles ("*.zip");//Check only. zip file if (FI.     Length > 0) {lst_DownLoadFileList.Items.Clear ();      foreach (FileInfo tmpfi in FI) {ListItem Tmpitem = new ListItem ();      Tmpitem.text = Tmpfi.name;     LST_DOWNLOADFILELIST.ITEMS.ADD (Tmpitem);    } lst_downloadfilelist.selectedindex = 0;     } else {if (Isalert) {Response.Write ("No files to download!"); }}}} catch (Exception ex) {ex.  ToString (); }} #endregion 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.