Tuesday 11 August 2015

Download files

  1.  Create interface for downloads method and path property.  Interface :  An interface contains only the signatures of methods, properties, events or indexers.  A class or struct that implements the interface must implement the members of the interface  that are specified in the interface definition.
     public interface downloads 
     {
         string path { get; set; }
         void download();
     }
    
  2.  create class name general and inherit the interface class in it  Inheritance :   Inheritance allows us to define a class in terms of another class,   which makes it easier to create and maintain an application.  set the property and method for download by using httpresponse download the file from server to local system.
     public class general  : downloads
     {
    
         public string path
         {
             get;
             set;
         }
    
         public void download()
         {
             using (FileStream fs = File.OpenRead(this.path))
             {
                 int length = (int)fs.Length;
                 byte[] buffer;
    
                 using (BinaryReader br = new BinaryReader(fs))
                 {
                     buffer = br.ReadBytes(length);
                 }
    
                 HttpContext.Current.Response.Clear();
                 HttpContext.Current.Response.Buffer = true;
                 HttpContext.Current.Response.AddHeader("content-disposition", 
                 String.Format("attachment;filename={0}",  Path.GetFileName(path)));
                 HttpContext.Current.Response.ContentType = 
                      "application/" + Path.GetExtension(path).Substring(1);
                 HttpContext.Current.Response.BinaryWrite(buffer);
                 HttpContext.Current.Response.End();
             }   //
         }
     }
    
    
    
  3.  create the object for class general and set the path to property  call the download method to make a download the file.  
      public void sDownload()
         {
             downloads obj = new general();
             obj.path = @"C:\GoogleBackup\googleService.txt";
             obj.download();
         }
    
    

No comments:

Post a Comment