Friday, June 22, 2012

Upload and Download files in C#.NET


<%@ Page Language="C#"  AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
html xmlns="http://www.w3.org/1999/xhtml">
head runat="server">
title>title>
head>
body>
form id="form1" runat="server">
div>
   table border="1" cellspacing="0" cellpadding="0" id="tbl">
   tbody>
   tr>
    td>
    
    td>
   tr>
   tbody>
 table>
 table border="1" cellspacing="0" cellpadding="0" id="tblButton">
 tbody>
 tr>
  td>
   
  td>
  td>
  asp:Button ID="btnDownload" Text="Download" runat="server" OnClick="btnDownload_Click" />
  td>
  tr>
tbody>
table>
div>
form>
body>
html>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
  }
  protected void btnUpload_Click(object sender, EventArgs e)
  {
    String filePath = FileUpload1.FileName;
    String strFileName = "";
    if (FileUpload1.PostedFile != null)
    {
       HttpPostedFile file = FileUpload1.PostedFile;
      //Get the size of the file so you can read the file
      int contentLen = file.ContentLength;
      if (contentLen > 0)
      {
          strFileName = Path.GetFileName(filePath);
          file.SaveAs(Server.MapPath(strFileName));
      }
  }
}
 protected void btnDownload_Click(object sender, EventArgs e)
 {
  string fileName = "Amazon.txt";
  string filePath = Server.MapPath(fileName);
  Response.Clear();
  Response.AppendHeader("content-disposition", "attachment; filename=" + filePath);
  Response.ContentType = "application/octet-stream";
  Response.WriteFile(filePath);
  Response.Flush();
  Response.End();
}
}

No comments:

Post a Comment