نحوه دانلود فایل از سرورFTP در ASP.Net
شنبه 28 شهریور 1394در این مقاله همراه با یک مثال نحوه دانلود فایل از وب سرور FTP در ASP.Net را به شما آموزش می دهیم.
از یک button برای دانلود فایل و GridView برای نمایش لیست فایل ها از فولدر FTP استفاده می شود. زمانی که روی دکمه Download کلیک شود، فایل از فولدر FTP دانلود خواهد شد.
زبان نشانه گذاری HTML
کد HTML زیر مربوط به کنترل GridView می باشد.
<asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="100" /> <asp:BoundField DataField="Size" HeaderText="Size (KB)" DataFormatString="{0:N2}" ItemStyle-Width="100" /> <asp:BoundField DataField="Date" HeaderText="Created Date" ItemStyle-Width="100" /> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile" CommandArgument='<%# Eval("Name") %>'></asp:LinkButton> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
فضای نام
فضاهای نام زیر را به پروژه خود اضافه می کنیم.
#C
using System.IO; using System.Net; using System.Data;
VB.Net
Imports System.IO Imports System.Net Imports System.Data
نمایش فهرست فایل ها از فولدر در ASP.Net:
در رویداد Page Load، یک FtpWebRequest با استفاده از متد set مربوط به propertyای به نام ListDirectoryDetails به وب سرور FTP ارسال می شود. زمانی که FtpWebResponse دریافت شود، با استفاده از کلاس StreamReader به صورت یک رشته خوانده می شود.
مثال FTP Response:
مثال زیر حاوی دو فایل و یک دایرکتوری می باشد. تفاوت بین فایل و دایرکتوری در اولین کاراکتر می باشد که اگر (-) باشد یک فایل و اگر حرف کوچک (d) باشد، یک دایرکتوری می باشد.
-rw-r--r-- 1 ftp ftp 845941 May 26 00:48 Desert.jpg -rw-r--r-- 1 ftp ftp 595284 May 26 00:48 Hydrangeas.jpg drwxr-xr-x 1 ftp ftp 0 May 26 00:51 Images
رشته Response با کاراکتر Enter جدا می شود(split) تا ورودی ها از هم تفکیک شوند و سپس هر ورودی با استفاده از کاراکتر Space برای به دست آوردن جزییات فایل مثل : نام ، سایز و تاریخ ایجاد تفکیک می شود.
جزییات واکشی شده درون یک DataTable قرار داده می گیرد که پس از آن به کنترل GridView متصل می شود.
#C
protected void Page_Load(object sender, EventArgs e) { //FTP Server URL. string ftp = "ftp://yourserver.com/"; //FTP Folder name. Leave blank if you want to list files from root folder. string ftpFolder = "Uploads/"; try { //Create FTP Request. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; //Enter FTP Server credentials. request.Credentials = new NetworkCredential("Username", "Password"); request.UsePassive = true; request.UseBinary = true; request.EnableSsl = false; //Fetch the Response and read it using StreamReader. FtpWebResponse response = (FtpWebResponse)request.GetResponse(); List<string> entries = new List<string>(); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { //Read the Response as String and split using New Line character. entries = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList(); } response.Close(); //Create a DataTable. DataTable dtFiles = new DataTable(); dtFiles.Columns.AddRange(new DataColumn[3] { new DataColumn("Name", typeof(string)), new DataColumn("Size", typeof(decimal)), new DataColumn("Date", typeof(string))}); //Loop and add details of each File to the DataTable. foreach (string entry in entries) { string[] splits = entry.Split(new string[] { " ", }, StringSplitOptions.RemoveEmptyEntries); //Determine whether entry is for File or Directory. bool isFile = splits[0].Substring(0, 1) != "d"; bool isDirectory = splits[0].Substring(0, 1) == "d"; //If entry is for File, add details to DataTable. if (isFile) { dtFiles.Rows.Add(); dtFiles.Rows[dtFiles.Rows.Count - 1]["Size"] = decimal.Parse(splits[4]) / 1024; dtFiles.Rows[dtFiles.Rows.Count - 1]["Date"] = string.Join(" ", splits[5], splits[6], splits[7]); string name = string.Empty; for (int i = 8; i < splits.Length; i++) { name = string.Join(" ", name, splits[i]); } dtFiles.Rows[dtFiles.Rows.Count - 1]["Name"] = name.Trim(); } } //Bind the GridView. gvFiles.DataSource = dtFiles; gvFiles.DataBind(); } catch (WebException ex) { throw new Exception((ex.Response as FtpWebResponse).StatusDescription); } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load 'FTP Server URL. Dim ftp As String = "ftp://yourserver.com/" 'FTP Folder name. Leave blank if you want to list files from root folder. Dim ftpFolder As String = "Uploads/" Try 'Create FTP Request. Dim request As FtpWebRequest = DirectCast(WebRequest.Create(ftp & ftpFolder), FtpWebRequest) request.Method = WebRequestMethods.Ftp.ListDirectoryDetails 'Enter FTP Server credentials. request.Credentials = New NetworkCredential("Username", "Password") request.UsePassive = True request.UseBinary = True request.EnableSsl = False 'Fetch the Response and read it using StreamReader. Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse) Dim entries As New List(Of String)() Using reader As New StreamReader(response.GetResponseStream()) 'Read the Response as String and split using New Line character. entries = reader.ReadToEnd().Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).ToList() End Using response.Close() 'Create a DataTable. Dim dtFiles As New DataTable() dtFiles.Columns.AddRange(New DataColumn(2) { _ New DataColumn("Name", GetType(String)), _ New DataColumn("Size", GetType(Decimal)), _ New DataColumn("Date", GetType(String))}) 'Loop and add details of each File to the DataTable. For Each entry As String In entries Dim splits As String() = entry.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries) 'Determine whether entry is for File or Directory. Dim isFile As Boolean = splits(0).Substring(0, 1) <> "d" Dim isDirectory As Boolean = splits(0).Substring(0, 1) = "d" 'If entry is for File, add details to DataTable. If isFile Then dtFiles.Rows.Add() dtFiles.Rows(dtFiles.Rows.Count - 1)("Size") = Decimal.Parse(splits(4)) / 1024 dtFiles.Rows(dtFiles.Rows.Count - 1)("Date") = String.Join(" ", splits(5), splits(6), splits(7)) Dim name As String = String.Empty For i As Integer = 8 To splits.Length - 1 name = String.Join(" ", name, splits(i)) Next dtFiles.Rows(dtFiles.Rows.Count - 1)("Name") = name.Trim() End If Next 'Bind the GridView. gvFiles.DataSource = dtFiles gvFiles.DataBind() Catch ex As WebException Throw New Exception(TryCast(ex.Response, FtpWebResponse).StatusDescription) End Try End Sub
دانلود یک فایل از فولدر FTP در ASP.Net:
هر ردیف GridView شامل یک دکمه Download برای دانلود کردن فایل مربوطه از فولدر FTP می باشد. زمانی که دکمه Download کلیک می شود یک FtpWebRequest با استفاده از متد set مربوط به propertyای به نام DownloadFile به وب سرور FTP ارسال می شود.
هنگامی که FtpWebResponse دریافت می شود، در شی کلاس MemoryStream کپی می شود که پس از آن در Response Stream به عنوان آرایه ای از بایت ها نوشته می شود و در نهایت به عنوان فایل دانلود می شود.
#C
protected void DownloadFile(object sender, EventArgs e) { string fileName = (sender as LinkButton).CommandArgument; //FTP Server URL. string ftp = "ftp://yourserver.com/"; //FTP Folder name. Leave blank if you want to Download file from root folder. string ftpFolder = "Uploads/"; try { //Create FTP Request. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName); request.Method = WebRequestMethods.Ftp.DownloadFile; //Enter FTP Server credentials. request.Credentials = new NetworkCredential("Username", "Password"); request.UsePassive = true; request.UseBinary = true; request.EnableSsl = false; //Fetch the Response and read it into a MemoryStream object. FtpWebResponse response = (FtpWebResponse)request.GetResponse(); using (MemoryStream stream = new MemoryStream()) { //Download the File. response.GetResponseStream().CopyTo(stream); Response.AddHeader("content-disposition", "attachment;filename=" + fileName); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.BinaryWrite(stream.ToArray()); Response.End(); } } catch (WebException ex) { throw new Exception((ex.Response as FtpWebResponse).StatusDescription); } }
VB.Net
Protected Sub DownloadFile(sender As Object, e As EventArgs) Dim fileName As String = TryCast(sender, LinkButton).CommandArgument 'FTP Server URL. Dim ftp As String = "ftp://yourserver.com/" 'FTP Folder name. Leave blank if you want to Download file from root folder. Dim ftpFolder As String = "Uploads/" Try 'Create FTP Request. Dim request As FtpWebRequest = DirectCast(WebRequest.Create(Convert.ToString(ftp & ftpFolder) & fileName), FtpWebRequest) request.Method = WebRequestMethods.Ftp.DownloadFile 'Enter FTP Server credentials. request.Credentials = New NetworkCredential("Username", "Password") request.UsePassive = True request.UseBinary = True request.EnableSsl = False 'Fetch the Response and read it into a MemoryStream object. Dim resp As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse) Using stream As New MemoryStream() 'Download the File. resp.GetResponseStream().CopyTo(stream) Response.AddHeader("content-disposition", "attachment;filename=" & fileName) Response.Cache.SetCacheability(HttpCacheability.NoCache) Response.BinaryWrite(stream.ToArray()) Response.End() End Using Catch ex As WebException Throw New Exception(TryCast(ex.Response, FtpWebResponse).StatusDescription) End Try End Sub
- ASP.net
- 2k بازدید
- 1 تشکر