Wednesday, December 5, 2012

Download files from a remote server folder using a Web-service

This Post is related to my article on Code project.

This is a very basic article which describes how to develop a simple application to download files from a folder in a remote server.

I'm using VS 2010 and a Web service to develop the application.
Using the code

First create a new website in VS 2010 and add a web-service. Then add the following Web methods to your web-service.

public void DownloadToBrowser(string fileName)
FileInfo file = new FileInfo(@"D:\DOCS\"+fileName);
Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); Context.Response.AddHeader("Content-Length", file.Length.ToString());
Context.Response.ContentType = "text/plain"; Context.Response.Flush(); Context.Response.TransmitFile(file.FullName); Context.Response.End();

public string[] GetFiles()
string[] Files = Directory.GetFiles(@"D:\DOCS\"); return Files;

D:\DOCS\ is the folder where the files reside in the remote server. Now add the Web-Service reference to your website and design your web form markup as follows:

<form id="form1" runat="server">
       <asp:Button ID="btnsearch" runat="server" Text="Search"
            onclick="btnsearch_Click" />
        <asp:TextBox ID="txtSearch" runat="server"
            Height="23px" Width="201px"></asp:TextBox>
        <br />
        <br />
        <asp:GridView ID="GridView1" runat="server"
                <asp:TemplateField HeaderText="Existing Files">
                 <asp:LinkButton ID="lbtnDownload"
                    Text='<%# Eval("FileName")%>' runat="server"
                    OnCommand ="lbtnDownload_Click"
                    CommandArgument='<%# Eval("FileName")%>'></asp:LinkButton>

Now you will see the interface with a Search button and a TextBox. You need to type the name of the file that you need to download in the TextBox and hit Search. Related documents will be added to the GridView. Add the following code to the search button click:

protected void btnsearch_Click(object sender, EventArgs e)
   FileSearchWebService FSW = new FileSearchWebService();
   string[] filePaths = FSW.GetFiles().AsEnumerable().Where(r=>r.Contains(txtSearch.Text)).ToArray();

   DataTable DT = new DataTable();
   DataColumn auto = new DataColumn("FileName", typeof(System.String));
   foreach (string item in filePaths)
    GridView1.DataSource = DT;

Now you need to call the web-service with the link button Click event to download the file. Then Run the application and see how it works

protected void lbtnDownload_Click(object sender, CommandEventArgs e)
    FileSearchWebService FSW = new FileSearchWebService();

No comments:
Write comments
Recommended Posts × +