Downloading File From External Server Using Credential In ASP.NET MVC

Introduction

This article explains how to download the files from external Server network path, using Server credentials in ASP.NET MVC. We cannot download the files from the external Server network path with our Server credential.

Read the article's link, given below, before reading this article because the following link helps you to learn the basics of the file download.

Background

We can download the files from the external Server, using credentials. Normally, we deploy our Application in the Web server but our files or documents are stored in the file Server. If need arises, connect the Web Server to the file Server, using credentials to download the files or documents through the Application because our files are stored in the file Server. If the files are stored in the external Server without credentials, we cannot download any files.

Important Class for Connecting External server

There are many classes which are important to connect the external Server, using credentials. One of the main classes is “NetworkCredential” Class. It provides the credentials for the password-based authentication schemes such as basic, digest, NTLM, and Kerberos authentication.

Name space for “NetworkCredential” Class is “System.Net” and assembly is “System (in System.dll)”. This class has many constructors but we are using two constructors mainly, which are-
  • NetworkCredential(String, SecureString)
  • NetworkCredential(String, SecureString, String)

NetworkCredential (String, SecureString) Initializes a new instance of the NetworkCredential class with the specified user name and the password.

NetworkCredential (String, SecureString, String) initializes a new instance of the NetworkCredential class with the specified user name, password, and the domain.

This class has many properties. These properties are given below-

  • Domain
  • Password
  • SecurePassword
  • UserName

The screenshots, given below, explain about the constructor and the properties.



Two inheritances are inheritances, which are inherited in NetworkCredential class. “ICredentials” and “ICredentialsByHost” are the two inheritances.




Important Function for Connecting External server

There are the two important functions, which are used to connect and disconnect the Server or the external Server.

  • WNetAddConnection2
  • WNetCancelConnection2

WNetAddConnection2

The WNetAddConnection2 function makes a connection to a network resource and can redirect a local device to the network resource.

  1. [DllImport("mpr.dll")]  
  2. private static extern int WNetAddConnection2(NetResource netResource,  
  3. string password, string username, int flags);  
WNetCancelConnection2

The WNetCancelConnection2 function cancels an existing network connection. You can also call the function to remove the remembered network connections,which are not currently connected.
  1. [DllImport("mpr.dll")]  
  2. private static extern int WNetAddConnection2(NetResource netResource,  
  3. string password, string username, int flags);  
Steps for File Download

The previous part of this article explains the basics of the file download, step by step. Here, small parts of the step are only different while the other steps are the same. Please find the below link for the previous part of this article. 
Step 1 - Open new MVC project, add new controller and add new action methods in which there is an added controller in the solution.
  1. using System.Linq;  
  2. using System.Web;  
  3. using System.Web.Mvc;  
  4.   
  5. namespace MutipleFileDownload.Controllers  
  6. {  
  7.     public class FileDownloadController : Controller  
  8.     {  
  9.         // GET: FileDownload  
  10.         public ActionResult FileHome()  
  11.         {  
  12.             return View();  
  13.         }  
  14.     }  
  15. }  

Step 2 - Right click on the specified action result, add view and add the code, given below, for simple view page design-

  1. @{  
  2. ViewBag.Title = "FileHome";  
  3. }  
  4.   
  5. <h2>Download Multiple Files As Compresed Format</h2>  
  6. @Html.ActionLink("Download Files","Download")  
Step 3 - Add a class in model folder and write the coding, given below, to connect to the external Server network. After connecting the external network, write the code to download file from the external Server network.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using MutipleFileDownload;  
  6. using System.IO;  
  7. using System.Runtime.InteropServices;  
  8. using System.Net;  
  9.   
  10. namespace MutipleFileDownload.Models  
  11. {  
  12.     public class NetworkConnection : IDisposable  
  13.     {  
  14.         string _networkName;  
  15.   
  16.         public NetworkConnection(string networkName,  
  17.             NetworkCredential credentials)  
  18.         {  
  19.             _networkName = networkName;  
  20.   
  21.             var netResource = new NetResource()  
  22.             {  
  23.                 Scope = ResourceScope.GlobalNetwork,  
  24.                 ResourceType = ResourceType.Disk,  
  25.                 DisplayType = ResourceDisplaytype.Share,  
  26.                 RemoteName = networkName  
  27.             };  
  28.   
  29.             var userName = string.IsNullOrEmpty(credentials.Domain)  
  30.                 ? credentials.UserName  
  31.                 : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);  
  32.   
  33.             var result = WNetAddConnection2(  
  34.                 netResource,  
  35.                 credentials.Password,  
  36.                 userName,  
  37.                 0);  
  38.   
  39.             if (result != 0)  
  40.             {  
  41.                 throw new System.ComponentModel.Win32Exception(result, "Error connecting to remote share" + credentials.Password.ToString() + "--" + credentials.Domain + credentials.UserName);  
  42.             }  
  43.         }  
  44.   
  45.         ~NetworkConnection()  
  46.         {  
  47.             Dispose(false);  
  48.         }  
  49.   
  50.         public void Dispose()  
  51.         {  
  52.             Dispose(true);  
  53.             GC.SuppressFinalize(this);  
  54.         }  
  55.   
  56.         protected virtual void Dispose(bool disposing)  
  57.         {  
  58.             WNetCancelConnection2(_networkName, 0, true);  
  59.         }  
  60.   
  61.         [DllImport("mpr.dll")]  
  62.         private static extern int WNetAddConnection2(NetResource netResource,  
  63.             string password, string username, int flags);  
  64.   
  65.         [DllImport("mpr.dll")]  
  66.         private static extern int WNetCancelConnection2(string name, int flags,  
  67.             bool force);  
  68.     }  
  69.   
  70.     [StructLayout(LayoutKind.Sequential)]  
  71.     public class NetResource  
  72.     {  
  73.         public ResourceScope Scope;  
  74.         public ResourceType ResourceType;  
  75.         public ResourceDisplaytype DisplayType;  
  76.         public int Usage;  
  77.         public string LocalName;  
  78.         public string RemoteName;  
  79.         public string Comment;  
  80.         public string Provider;  
  81.     }  
  82.   
  83.     public enum ResourceScope : int  
  84.     {  
  85.         Connected = 1,  
  86.         GlobalNetwork,  
  87.         Remembered,  
  88.         Recent,  
  89.         Context  
  90.     };  
  91.   
  92.     public enum ResourceType : int  
  93.     {  
  94.         Any = 0,  
  95.         Disk = 1,  
  96.         Print = 2,  
  97.         Reserved = 8,  
  98.     }  
  99.   
  100.     public enum ResourceDisplaytype : int  
  101.     {  
  102.         Generic = 0x0,  
  103.         Domain = 0x01,  
  104.         Server = 0x02,  
  105.         Share = 0x03,  
  106.         File = 0x04,  
  107.         Group = 0x05,  
  108.         Network = 0x06,  
  109.         Root = 0x07,  
  110.         Shareadmin = 0x08,  
  111.         Directory = 0x09,  
  112.         Tree = 0x0a,  
  113.         Ndscontainer = 0x0b  
  114.     }  
  115.     public class FileDownloads  
  116.     {  
  117.   
  118.     }  
  119. }  
Step 4 - In “FileDownload.cs” file, add “GetFile()” in side of FileDownloads class. DetFile methods contains the code, given below. This code gets the file from the specified share path in the external Server.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using MutipleFileDownload;  
  6. using System.IO;  
  7. using System.Runtime.InteropServices;  
  8. using System.Net;  
  9.   
  10. namespace MutipleFileDownload.Models  
  11. {  
  12.     public class NetworkConnection : IDisposable  
  13.     {  
  14.         string _networkName;  
  15.   
  16.         public NetworkConnection(string networkName,  
  17.             NetworkCredential credentials)  
  18.         {  
  19.             _networkName = networkName;  
  20.   
  21.             var netResource = new NetResource()  
  22.             {  
  23.                 Scope = ResourceScope.GlobalNetwork,  
  24.                 ResourceType = ResourceType.Disk,  
  25.                 DisplayType = ResourceDisplaytype.Share,  
  26.                 RemoteName = networkName  
  27.             };  
  28.   
  29.             var userName = string.IsNullOrEmpty(credentials.Domain)  
  30.                 ? credentials.UserName  
  31.                 : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);  
  32.   
  33.             var result = WNetAddConnection2(  
  34.                 netResource,  
  35.                 credentials.Password,  
  36.                 userName,  
  37.                 0);  
  38.   
  39.             if (result != 0)  
  40.             {  
  41.                 throw new System.ComponentModel.Win32Exception(result, "Error connecting to remote share" + credentials.Password.ToString() + "--" + credentials.Domain + credentials.UserName);  
  42.             }  
  43.         }  
  44.   
  45.         ~NetworkConnection()  
  46.         {  
  47.             Dispose(false);  
  48.         }  
  49.   
  50.         public void Dispose()  
  51.         {  
  52.             Dispose(true);  
  53.             GC.SuppressFinalize(this);  
  54.         }  
  55.   
  56.         protected virtual void Dispose(bool disposing)  
  57.         {  
  58.             WNetCancelConnection2(_networkName, 0, true);  
  59.         }  
  60.   
  61.         [DllImport("mpr.dll")]  
  62.         private static extern int WNetAddConnection2(NetResource netResource,  
  63.             string password, string username, int flags);  
  64.   
  65.         [DllImport("mpr.dll")]  
  66.         private static extern int WNetCancelConnection2(string name, int flags,  
  67.             bool force);  
  68.     }  
  69.   
  70.     [StructLayout(LayoutKind.Sequential)]  
  71.     public class NetResource  
  72.     {  
  73.         public ResourceScope Scope;  
  74.         public ResourceType ResourceType;  
  75.         public ResourceDisplaytype DisplayType;  
  76.         public int Usage;  
  77.         public string LocalName;  
  78.         public string RemoteName;  
  79.         public string Comment;  
  80.         public string Provider;  
  81.     }  
  82.   
  83.     public enum ResourceScope : int  
  84.     {  
  85.         Connected = 1,  
  86.         GlobalNetwork,  
  87.         Remembered,  
  88.         Recent,  
  89.         Context  
  90.     };  
  91.   
  92.     public enum ResourceType : int  
  93.     {  
  94.         Any = 0,  
  95.         Disk = 1,  
  96.         Print = 2,  
  97.         Reserved = 8,  
  98.     }  
  99.   
  100.     public enum ResourceDisplaytype : int  
  101.     {  
  102.         Generic = 0x0,  
  103.         Domain = 0x01,  
  104.         Server = 0x02,  
  105.         Share = 0x03,  
  106.         File = 0x04,  
  107.         Group = 0x05,  
  108.         Network = 0x06,  
  109.         Root = 0x07,  
  110.         Shareadmin = 0x08,  
  111.         Directory = 0x09,  
  112.         Tree = 0x0a,  
  113.         Ndscontainer = 0x0b  
  114.     }  
  115.     public class FileDownloads  
  116.     {  
  117.         public List<FileInfo> GetFile()  
  118.         {  
  119.               
  120.             List<FileInfo> listFiles = new List<FileInfo>();  
  121.               
  122.             NetworkCredential NCredentials = new NetworkCredential("userNmae","passWord","DomainName");  
  123.             //userName   --> Serevr User Name  
  124.             //passWord   --> Server Password  
  125.             //DomainName --> Yourdomain Name  
  126.   
  127.             // If server your server not in domain user below line  
  128.             //NetworkCredential NCredentials = new NetworkCredential("userNmae","passWord");  
  129.   
  130.             //Path For download From Network Path.  
  131.               
  132.             using (new NetworkConnection(@"\\servername\shareFolderName", NCredentials))  
  133.             {  
  134.   
  135.                 string fileSavePath = @"\\servername\shareFolderName";  
  136.                 DirectoryInfo dirInfo = new DirectoryInfo(fileSavePath);  
  137.   
  138.                 int i = 0;  
  139.                 foreach (var item in dirInfo.GetFiles())  
  140.                 {  
  141.                     listFiles.Add(new FileInfo()  
  142.                     {  
  143.   
  144.                         FileId = i + 1,  
  145.                         FileName = item.Name,  
  146.                         FilePath = dirInfo.FullName + @"\" + item.Name  
  147.   
  148.                     });  
  149.                     i = i + 1;  
  150.                 }  
  151.             }  
  152.             return listFiles;  
  153.   
  154.         }  
  155.   
  156.     }  
  157. }  
Step 5 - Add another action method in the controller. This action method is used to convert multiple files as ZIP files and will be downloading. All the files are downloaded from the specified external Server's shared path. The coding, given below, is used to convert the files as a ZIP file. 
  1. using MutipleFileDownload.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System.IO.Compression;  
  6. using System.Linq;  
  7. using System.Web;  
  8. using System.Web.Mvc;  
  9.   
  10. namespace MutipleFileDownload.Controllers  
  11. {  
  12.     public class FileDownloadController : Controller  
  13.     {  
  14.         // GET: FileDownload  
  15.         public ActionResult FileHome()  
  16.         {  
  17.             return View();  
  18.         }  
  19.         public ActionResult Download()  
  20.         {  
  21.                 FileDownloads obj = new FileDownloads();  
  22.                 //////int CurrentFileID = Convert.ToInt32(FileID);  
  23.                 var filesCol = obj.GetFile().ToList();  
  24.   
  25.                 using (var memoryStream = new MemoryStream())  
  26.                 {  
  27.                     using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))  
  28.                     {  
  29.                         for (int i = 0; i < filesCol.Count; i++)  
  30.                         {  
  31.                             ziparchive.CreateEntryFromFile(filesCol[i].FilePath, filesCol[i].FileName);  
  32.                             //  ziparchive.CreateEntryFromFile(Server.MapPath("~/images/img_Download.PNG"), "img_Download.PNG");  
  33.                         }  
  34.                     }  
  35.   
  36.                     return File(memoryStream.ToArray(), "application/zip""Attachments.zip");  
  37.                 }  
  38.         }  
  39.   
  40.     }  
  41.   
  42. }  
Step 6 - Finally build and run the Application. After running the Application, click download button. Files will be downloading as a ZIP file from the specified external Server shared path.



Note- I have attached the source code in this article. After downloading the source code, change your Server credential and shared path in FileDownload.cs file and run will be executing successfully.


Conclusion

This articles help you to learn the download of the multiple files from the external Server in an easy manner. This helps the students and those, who have learned MVC in recent times. Using the steps mentioned in this article, we can download the files from the external Server's shared path. 


Similar Articles