asp.net ftp file Upload class

Source: Internet
Author: User
Tags create directory file upload ftp ftp file int size

Only to achieve the basic upload, download, determine whether the file exists and my practical application of the most important based on the selected remote file address automatically create related directory features

Specific code Download: Ftphelper

Editor inserts the code always complains the error only to be able to paste directly, the sweat ...

Using System;

Using System.Collections.Generic;


Using System.Linq;


Using System.Text;


Using System.Net;


Using System.IO;


Using System.Text.RegularExpressions;


Using System.Globalization;


Namespace System.helper


{


<summary>


Founder: Lazy Fat Rabbit


FTP Operation class


Supports only basic file uploads, downloads, directory recursive creation, file directory list acquisition


</summary>


public class Ftphelper


{


#region Properties


<summary>


Gets or sets the user name


</summary>


public string UserName {get; set;}


<summary>


Get or set a password


</summary>


public string Password {get; set;}


<summary>


Exception information


</summary>


public string ErrorMsg {get; set;}


<summary>


Exception


</summary>


Public Exception Exception {get; set;}


<summary>


State


</summary>


Public Ftpstatuscode StatusCode {get; set;}


<summary>


Status description


</summary>


public string Statusdescription {get; set;}


<summary>


Gets or sets the FTP server address


</summary>


Public URI Uri {get; set;}


<summary>


Gets or is the encoding used to read the file, directory list, default to UTF-8


</summary>


Public Encoding Encode {get; set;}


#endregion


#region Constructors
Public ftphelper (URI Uri, string Username, string password)
{
This. uri = URI;
This. UserName = UserName;
This. Password = Password;
This. Encode = encoding.getencoding ("Utf-8");
}
#endregion




#region Establish a connection


<summary>


Set up an FTP link to return the request object


</summary>


<param name= "uri" >ftp address </param>


<param name= "method" > Operation command (WEBREQUESTMETHODS.FTP) </param>


<returns></returns>


Private FtpWebRequest createrequest (Uri Uri, string method)


{


Try


{


FtpWebRequest request = (ftpwebrequest) webrequest.create (URI);


Request. Credentials = new NetworkCredential (this. UserName, this. Password);//Specifies the user name and password to log on to the FTP server.


Request. KeepAlive = false;//Specifies whether the connection should be closed or closed after the request completes, and the default is True


Request. Usepassive = true;//Specifies to use passive mode, default to True


Request. Usebinary = true;//indicates that the server is transferring binary data. False, indicating that the data is text. The default value is True


Request. Enablessl = false;//True if control and data transfer is encrypted. Otherwise, false. Default value is False


Request. Method = method;


return request;


}


catch (Exception ex)


{


Throw ex;


}


}




<summary>


Set up an FTP link to return the response object


</summary>


<param name= "uri" >ftp address </param>


<param name= "method" > Operation command (WEBREQUESTMETHODS.FTP) </param>


<returns></returns>


Private FtpWebResponse createresponse (Uri Uri, string method)


{


Try


{


FtpWebRequest request = Createrequest (Uri, method);


FtpWebResponse response = (ftpwebresponse) request. GetResponse ();


This. StatusCode = Response. StatusCode;


This. Statusdescription = Response. Statusdescription;


return response;


}


catch (WebException ex)


{


FtpWebResponse response = ex. Response as FtpWebResponse;


if (response!= null)


{


This. StatusCode = Response. StatusCode;


This. Statusdescription = Response. Statusdescription;


}


Throw ex;


}


}


#endregion




#region Upload File


<summary>


Upload file to FTP server, if file already exists auto overwrite


This method does not automatically create a directory of remote paths


</summary>


<param name= "Localfilepath" > local filename with full path </param>


<param name= "Remotefilepath" > to save the full file name on the FTP server </param>


public bool UploadFile (string Localfilepath, String remotefilepath)


{


Return UploadFile (Localfilepath, Remotefilepath, false);


}


<summary>


Upload file to FTP server, if file already exists auto overwrite


</summary>


<param name= "Localfilepath" > local filename with full path </param>


<param name= "Remotefilepath" > to save the full file name on the FTP server </param>


<param name= "Autocreatedirectory" > whether the file directory is automatically recursively created </param>


<returns></returns>


public bool UploadFile (string Localfilepath, String remotefilepath, bool autocreatedirectory)


{


Try


{


Automatically recursively create a directory


if (autocreatedirectory)


{


if (! CreateDirectory (Path.getdirectoryname (Remotefilepath))


{


Recursive Create directory failed, return false


return false;


}


}


FileInfo Fileinf = new FileInfo (Localfilepath);


if (!fileinf.exists)


{


throw new FileNotFoundException (string. Format ("Local file does not exist: {0}!", localfilepath));


}


FtpWebRequest request = Createrequest (The new Uri (this. Uri + Remotefilepath), WebRequestMethods.Ftp.UploadFile);


Request. ContentLength = Fileinf.length;




int contentlen = 0;


Buffer 2kb


byte[] buff = new byte[2048];


using (FileStream fs = Fileinf.openread ())


{


using (Stream stream = Request. GetRequestStream ())


{


while (Contentlen = fs. Read (buff, 0, buff. Length)) > 0)


{


Stream. Write (Buff, 0, Contentlen);


}


}


}


return true;


}


catch (Exception ex)


{


This. Exception = ex;


This. ErrorMsg = ex. message;


}


return false;


}


#endregion




#region Download files


<summary>


Downloading files from an FTP server


</summary>


<param name= "Remotefilepath" > Remote full file name </param>


<param name= "Localfilepath" > local filename with full path </param>


public bool DownloadFile (string Remotefilepath, String localfilepath)


{


Try


{


String LocalDirector = Path.getdirectoryname (Localfilepath);


if (! Directory.Exists (LocalDirector))


{


Directory.CreateDirectory (LocalDirector);


}




FtpWebResponse response = Createresponse (The new Uri (this. Uri + Remotefilepath), WebRequestMethods.Ftp.DownloadFile);


byte[] buffer = new byte[2048];


int bytescount = 0;


Stream stream = Response. GetResponseStream ();


using (FileStream fs = new FileStream (Localfilepath, FileMode.Create))


{


while (Bytescount = stream. Read (buffer, 0, buffer.) Length)) > 0)


{


Fs. Write (buffer, 0, bytescount);


}


}


return true;


}


catch (Exception ex)


{


This. Exception = ex;


This. ErrorMsg = ex. message;


}


return false;


}


#endregion




#region Move, rename a file


<summary>


Moving remote file files


</summary>


<param name= "Remotefilename" > Remote file name </param>


<param name= "NewFileName" > New file name </param>


<returns></returns>


public bool MoveFile (string remotefilename, String newfilename)


{


Return ReName (Remotefilename, NewFileName);


}


<summary>


Renaming remote Files


</summary>


<param name= "Remotefilename" > Remote file name </param>


<param name= "NewFileName" > New file name </param>


<returns></returns>


public bool ReName (string remotefilename, String newfilename)


{


Try


{


if (remotefilename!= newfilename)


{


FtpWebRequest request = Createrequest (The new Uri (this. Uri + remotefilename), WebRequestMethods.Ftp.Rename);


Request. Renameto = NewFileName;


Request. GetResponse ();


}


return true;


}


catch (WebException ex)


{


This. ErrorMsg = ex. message;


This. Exception = ex;


FtpWebResponse response = ex. Response as FtpWebResponse;


if (response!= null)


{


This. StatusCode = Response. StatusCode;


This. Statusdescription = Response. Statusdescription;


}


}


return false;


}


#endregion




#region Delete Files


<summary>


Delete remote Files


</summary>


<param name= "FileName" ></param>


<returns> return true successfully, otherwise return false</returns>


public bool DeleteFile (string fileName)


{


Try


{


Createresponse the new Uri (this. Uri + fileName), WebRequestMethods.Ftp.DeleteFile);


return true;


}


catch (Exception ex)


{


This. Exception = ex;


This. ErrorMsg = ex. message;


}


return false;


}


#endregion


Create a directory #region recursively
<summary>
Recursively creates a directory that does not have a check before the directory is created
</summary>
<param name= "Remotedirectory" ></param>
public bool CreateDirectory (string remotedirectory)
{
Return CreateDirectory (Remotedirectory, false);
}




&lt;summary&gt;


To create a directory recursively on an FTP server


&lt;/summary&gt;


&lt;param name= "Remotedirectory" &gt; Directories to be created &lt;/param&gt;


&lt;param name= "Autocheckexist" &gt; whether a directory exists before creating a directory &lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public bool CreateDirectory (string remotedirectory, bool autocheckexist)


{


Try


{


String parentdirector = "/";


if (!string. IsNullOrEmpty (remotedirectory))


{


Remotedirectory = Remotedirectory.replace ("", "/");


string[] directors = remotedirectory.split (new char[] {'/'}, Stringsplitoptions.removeemptyentries);


foreach (string Director in directors)


{


if (!parentdirector.endswith ("/")) Parentdirector + = "/";


if (autocheckexist)


{


if (! Directoryexist (Parentdirector, director))


Createresponse the new Uri (this. Uri + Parentdirector + director), WebRequestMethods.Ftp.MakeDirectory);


}


Else


{


Try


{


Createresponse the new Uri (this. Uri + Parentdirector + director), WebRequestMethods.Ftp.MakeDirectory);


}


catch (WebException ex)


{


if (this. StatusCode!= ftpstatuscode.actionnottakenfileunavailable)


{


Throw ex;


}


}


}


Parentdirector + = Director;


}


}


return true;


}


catch (WebException ex)


{


This. Exception = ex;


This. ErrorMsg = ex. message;


}


return false;


}




&lt;summary&gt;


Detects if a specified directory name exists under the specified directory


&lt;/summary&gt;


&lt;param name= "Parentdirector" &gt;&lt;/param&gt;


&lt;param name= "DirectoryName" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


private bool Directoryexist (string parentdirector, String directoryname)


{


list&lt;filestruct&gt; list = Getfileanddirectorylist (Parentdirector);


foreach (filestruct fstruct in list)


{


if (fstruct. Isdirectory &amp;&amp; fstruct. Name = = directoryname)


{


return true;


}


}


return false;


}


#endregion




#region detect if a file already exists


&lt;summary&gt;


Detects if a specified file exists on the FTP server


Chinese file name If there is no correct detection now is willing to can be caused by coding problems


Please call this. Encode file encoding settings, the default is UTF-8, generally changed to GB2312 will be able to correctly identify


&lt;/summary&gt;


&lt;param name= "Remotefilepath" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


public bool FileExist (string Remotefilepath)


{


list&lt;filestruct&gt; list = Getfileanddirectorylist (Path.getdirectoryname (Remotefilepath));


foreach (filestruct fstruct in list)


{


if (!fstruct. Isdirectory &amp;&amp; fstruct. Name = = Path.getfilename (Remotefilepath))


{


return true;


}


}


return false;


}


#endregion




#region Directory, file list


&lt;summary&gt;


Get all files and directories under the specified directory on the FTP server


If you get the Chinese files, directories famous garbled phenomenon


Please call this. Encode file encoding settings, the default is UTF-8, generally changed to GB2312 will be able to correctly identify


&lt;/summary&gt;


&lt;param name= "Direcotry" &gt;&lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


Public list&lt;filestruct&gt; getfileanddirectorylist (string direcotry)


{


Try


{


list&lt;filestruct&gt; list = new list&lt;filestruct&gt; ();


string str = NULL;


WebRequestMethods.Ftp.ListDirectoryDetails can list all the files and directories


WebRequestMethods.Ftp.ListDirectory can only list file lists of directories


FtpWebResponse response = Createresponse (The new Uri (this. Uri.tostring () + direcotry), WebRequestMethods.Ftp.ListDirectoryDetails);


Stream stream = Response. GetResponseStream ();




using (StreamReader sr = new StreamReader (stream, this.) Encode))


{


str = Sr. ReadToEnd ();


}


string[] filelist = str. Split (new char[] {' R ', ' n '}, stringsplitoptions.removeemptyentries);


Efilelistformat format = Judgefilelistformat (filelist);


if (!string. IsNullOrEmpty (str) &amp;&amp; format!= efilelistformat.unknown)


{


List = parsefilestruct (filelist, format);


}


return list;


}


catch (WebException ex)


{


Throw ex;


}


}




&lt;summary&gt;


Parse file list information return to file list


&lt;/summary&gt;


&lt;param name= "FileList" &gt;&lt;/param&gt;


&lt;param name= "format" &gt; file list format &lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


Private list&lt;filestruct&gt; parsefilestruct (string[] filelist, Efilelistformat format)


{


list&lt;filestruct&gt; list = new list&lt;filestruct&gt; ();


if (format = = Efilelistformat.unixformat)


{


foreach (string info in filelist)


{


Filestruct fstuct = new Filestruct ();


Fstuct. Origin = info. Trim ();


Fstuct. Originarr = fstuct. Origin.split (new char[] {'}, stringsplitoptions.removeemptyentries);


if (fstuct. Originarr.length = 9)


{


Fstuct. Flags = fstuct. ORIGINARR[0];


Fstuct. Isdirectory = (fstuct. Flags[0] = = = ' d ');


Fstuct. Owner = fstuct. ORIGINARR[2];


Fstuct. Group = fstuct. ORIGINARR[3];


Fstuct. Size = Convert.ToInt32 (fstuct. ORIGINARR[4]);


if (fstuct. ORIGINARR[7]. Contains (":"))


{


Fstuct. ORIGINARR[7] = DateTime.Now.Year + "" + fstuct. ORIGINARR[7];


}


Fstuct. UpdateTime = DateTime.Parse (string. Format (' {0} {1} {2} ', Fstuct. ORIGINARR[5], fstuct. ORIGINARR[6], fstuct. ORIGINARR[7]));


Fstuct. Name = fstuct. ORIGINARR[8];


if (fstuct. Name!= "." &amp;&amp; fstuct. Name!= "..")


{


List. ADD (fstuct);


}


}




}


}


else if (format = = Efilelistformat.windowsformat)


{


foreach (string info in filelist)


{


Filestruct fstuct = new Filestruct ();


Fstuct. Origin = info. Trim ();


Fstuct. Originarr = fstuct. Origin.split (new char[] {'}, stringsplitoptions.removeemptyentries);


if (fstuct. Originarr.length = 4)


{


DateTimeFormatInfo usdate = new CultureInfo ("en-us", false). DateTimeFormat;


Usdate.shorttimepattern = "T";


Fstuct. UpdateTime = DateTime.Parse (fstuct. Originarr[0] + "" + fstuct. ORIGINARR[1], usdate);




Fstuct. Isdirectory = (fstuct. ORIGINARR[2] = = "&lt;DIR&gt;");


if (!fstuct. Isdirectory)


{


Fstuct. Size = Convert.ToInt32 (fstuct. ORIGINARR[2]);


}


Fstuct. Name = fstuct. ORIGINARR[3];


if (fstuct. Name!= "." &amp;&amp; fstuct. Name!= "..")


{


List. ADD (fstuct);


}


}


}


}


return list;


}




&lt;summary&gt;


How to determine the File List window mode or UNIX mode


&lt;/summary&gt;


&lt;param name= "FileList" &gt; File Information list &lt;/param&gt;


&lt;returns&gt;&lt;/returns&gt;


Private Efilelistformat Judgefilelistformat (string[] filelist)


{


foreach (String str in filelist)


{


if (str. Length &gt; Ten &amp;&amp; regex.ismatch (str. Substring (0), (-|d) (-|r) (-|w) (-|x) (-|r) (-|w) (-|x) (-|r) (-|w) (-|x)))


{


return efilelistformat.unixformat;


}


else if (str. Length &gt; 8 &amp;&amp; regex.ismatch (str. Substring (0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]")


{


return efilelistformat.windowsformat;


}


}


return efilelistformat.unknown;


}




Private Filestruct Parsefilestructfromwindowsstylerecord (string record)


{


Filestruct f = new filestruct ();


String processstr = Record.trim ();


String datestr = Processstr. Substring (0, 8);


Processstr = (processstr. Substring (8, Processstr. Length-8)). Trim ();


String timestr = Processstr. Substring (0, 7);


Processstr = (processstr. Substring (7, Processstr. Length-7)). Trim ();


DateTimeFormatInfo Mydtfi = new CultureInfo ("en-us", false). DateTimeFormat;


Mydtfi.shorttimepattern = "T";


F.updatetime = DateTime.Parse (Datestr + "" + Timestr, Mydtfi);


if (processstr. Substring (0, 5) = = "&lt;DIR&gt;")


{


F.isdirectory = true;


Processstr = (processstr. Substring (5, Processstr. Length-5)). Trim ();


}


Else


{


string[] STRs = processstr.   Split (new char[] {'}, stringsplitoptions.removeemptyentries); true);


Processstr = strs[1];


F.isdirectory = false;


}


F.name = Processstr;


return F;


}


#endregion


}




#region File Structure


&lt;summary&gt;


File list format


&lt;/summary&gt;


public enum Efilelistformat


{


&lt;summary&gt;


UNIX file format


&lt;/summary&gt;


Unixformat,


&lt;summary&gt;


Window file format


&lt;/summary&gt;


Windowsformat,


&lt;summary&gt;


Unknown format


&lt;/summary&gt;


Unknown


}




public struct FILESTRUCT


{


public string Origin {get; set;}


Public string[] Originarr {get; set;}


public string Flags {get; set;}


&lt;summary&gt;


Owner


&lt;/summary&gt;


public string Owner {get; set;}


public string Group {get; set;}


&lt;summary&gt;


is a directory


&lt;/summary&gt;


public bool Isdirectory {get; set;}


&lt;summary&gt;


File or directory update time


&lt;/summary&gt;


Public DateTime updatetime {get; set;}


&lt;summary&gt;


File or directory Name


&lt;/summary&gt;


public string Name {get; set;}


<summary>
File size (directory is always 0)
</summary>
public int Size {get; set;}
}
#endregion


}

SOURCE Download Address

Http://down.111cn.net/down/code/net/2011/0612/23160.html

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.