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.
- [DllImport("mpr.dll")]
- private static extern int WNetAddConnection2(NetResource netResource,
- 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.
- [DllImport("mpr.dll")]
- private static extern int WNetAddConnection2(NetResource netResource,
- 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.
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MutipleFileDownload.Controllers
- {
- public class FileDownloadController : Controller
- {
-
- public ActionResult FileHome()
- {
- return View();
- }
- }
- }
Step 2 - Right click on the specified action result, add view and add the code, given below, for simple view page design-
- @{
- ViewBag.Title = "FileHome";
- }
-
- <h2>Download Multiple Files As Compresed Format</h2>
- @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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using MutipleFileDownload;
- using System.IO;
- using System.Runtime.InteropServices;
- using System.Net;
-
- namespace MutipleFileDownload.Models
- {
- public class NetworkConnection : IDisposable
- {
- string _networkName;
-
- public NetworkConnection(string networkName,
- NetworkCredential credentials)
- {
- _networkName = networkName;
-
- var netResource = new NetResource()
- {
- Scope = ResourceScope.GlobalNetwork,
- ResourceType = ResourceType.Disk,
- DisplayType = ResourceDisplaytype.Share,
- RemoteName = networkName
- };
-
- var userName = string.IsNullOrEmpty(credentials.Domain)
- ? credentials.UserName
- : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);
-
- var result = WNetAddConnection2(
- netResource,
- credentials.Password,
- userName,
- 0);
-
- if (result != 0)
- {
- throw new System.ComponentModel.Win32Exception(result, "Error connecting to remote share" + credentials.Password.ToString() + "--" + credentials.Domain + credentials.UserName);
- }
- }
-
- ~NetworkConnection()
- {
- Dispose(false);
- }
-
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- WNetCancelConnection2(_networkName, 0, true);
- }
-
- [DllImport("mpr.dll")]
- private static extern int WNetAddConnection2(NetResource netResource,
- string password, string username, int flags);
-
- [DllImport("mpr.dll")]
- private static extern int WNetCancelConnection2(string name, int flags,
- bool force);
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public class NetResource
- {
- public ResourceScope Scope;
- public ResourceType ResourceType;
- public ResourceDisplaytype DisplayType;
- public int Usage;
- public string LocalName;
- public string RemoteName;
- public string Comment;
- public string Provider;
- }
-
- public enum ResourceScope : int
- {
- Connected = 1,
- GlobalNetwork,
- Remembered,
- Recent,
- Context
- };
-
- public enum ResourceType : int
- {
- Any = 0,
- Disk = 1,
- Print = 2,
- Reserved = 8,
- }
-
- public enum ResourceDisplaytype : int
- {
- Generic = 0x0,
- Domain = 0x01,
- Server = 0x02,
- Share = 0x03,
- File = 0x04,
- Group = 0x05,
- Network = 0x06,
- Root = 0x07,
- Shareadmin = 0x08,
- Directory = 0x09,
- Tree = 0x0a,
- Ndscontainer = 0x0b
- }
- public class FileDownloads
- {
-
- }
- }
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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using MutipleFileDownload;
- using System.IO;
- using System.Runtime.InteropServices;
- using System.Net;
-
- namespace MutipleFileDownload.Models
- {
- public class NetworkConnection : IDisposable
- {
- string _networkName;
-
- public NetworkConnection(string networkName,
- NetworkCredential credentials)
- {
- _networkName = networkName;
-
- var netResource = new NetResource()
- {
- Scope = ResourceScope.GlobalNetwork,
- ResourceType = ResourceType.Disk,
- DisplayType = ResourceDisplaytype.Share,
- RemoteName = networkName
- };
-
- var userName = string.IsNullOrEmpty(credentials.Domain)
- ? credentials.UserName
- : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);
-
- var result = WNetAddConnection2(
- netResource,
- credentials.Password,
- userName,
- 0);
-
- if (result != 0)
- {
- throw new System.ComponentModel.Win32Exception(result, "Error connecting to remote share" + credentials.Password.ToString() + "--" + credentials.Domain + credentials.UserName);
- }
- }
-
- ~NetworkConnection()
- {
- Dispose(false);
- }
-
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- WNetCancelConnection2(_networkName, 0, true);
- }
-
- [DllImport("mpr.dll")]
- private static extern int WNetAddConnection2(NetResource netResource,
- string password, string username, int flags);
-
- [DllImport("mpr.dll")]
- private static extern int WNetCancelConnection2(string name, int flags,
- bool force);
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public class NetResource
- {
- public ResourceScope Scope;
- public ResourceType ResourceType;
- public ResourceDisplaytype DisplayType;
- public int Usage;
- public string LocalName;
- public string RemoteName;
- public string Comment;
- public string Provider;
- }
-
- public enum ResourceScope : int
- {
- Connected = 1,
- GlobalNetwork,
- Remembered,
- Recent,
- Context
- };
-
- public enum ResourceType : int
- {
- Any = 0,
- Disk = 1,
- Print = 2,
- Reserved = 8,
- }
-
- public enum ResourceDisplaytype : int
- {
- Generic = 0x0,
- Domain = 0x01,
- Server = 0x02,
- Share = 0x03,
- File = 0x04,
- Group = 0x05,
- Network = 0x06,
- Root = 0x07,
- Shareadmin = 0x08,
- Directory = 0x09,
- Tree = 0x0a,
- Ndscontainer = 0x0b
- }
- public class FileDownloads
- {
- public List<FileInfo> GetFile()
- {
-
- List<FileInfo> listFiles = new List<FileInfo>();
-
- NetworkCredential NCredentials = new NetworkCredential("userNmae","passWord","DomainName");
-
-
-
-
-
-
-
-
-
- using (new NetworkConnection(@"\\servername\shareFolderName", NCredentials))
- {
-
- string fileSavePath = @"\\servername\shareFolderName";
- DirectoryInfo dirInfo = new DirectoryInfo(fileSavePath);
-
- int i = 0;
- foreach (var item in dirInfo.GetFiles())
- {
- listFiles.Add(new FileInfo()
- {
-
- FileId = i + 1,
- FileName = item.Name,
- FilePath = dirInfo.FullName + @"\" + item.Name
-
- });
- i = i + 1;
- }
- }
- return listFiles;
-
- }
-
- }
- }
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.
- using MutipleFileDownload.Models;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.IO.Compression;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MutipleFileDownload.Controllers
- {
- public class FileDownloadController : Controller
- {
-
- public ActionResult FileHome()
- {
- return View();
- }
- public ActionResult Download()
- {
- FileDownloads obj = new FileDownloads();
-
- var filesCol = obj.GetFile().ToList();
-
- using (var memoryStream = new MemoryStream())
- {
- using (var ziparchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
- {
- for (int i = 0; i < filesCol.Count; i++)
- {
- ziparchive.CreateEntryFromFile(filesCol[i].FilePath, filesCol[i].FileName);
-
- }
- }
-
- return File(memoryStream.ToArray(), "application/zip", "Attachments.zip");
- }
- }
-
- }
-
- }
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.