a blog for those who code

Friday, 29 August 2014

Using UNC path for Storing and Retrieving Files in ASP Net

In this post we will show you how to store and retrieve files in the remote file server using UNC path. UNC is a naming convention used to specify and map network drives in Microsoft Windows.

You need to have two server FileServer and WebServer. You also need admin rights for both the servers. In both the server you have to create a user with the same username and password. Lets say, UserName : TestUser, Password = pwd. Now in IIS you have to Edit permissions of your Website as shown below.
Now on the Security Tab, add TestUser and give all the permissions (Full Control, Modify. Read & execute, etc..) to that user.
In the FileServer create a Folder (TestFolder) and share that folder with the newly created user (TestUser). After sharing you will get a path as //YourComputerName/TestFolder (so called UNC path).

Now implement impersonation in Asp.Net as shown below.
While doing this you might get errors like :

1. Could not load file or assembly or one of its dependencies. Access is denied.

To fix this you have to add permissions (newly created User's) to the "Temporary Asp.Net folder"

Location of Temporary Asp.Net folder is -
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files

2. Logon failure: unknown user name or bad password

If you get this error make sure that the username and password of both the servers are same and you have added impersonation feature in webconfig. In the code behind you can use the below code to save the file in the remote server...

protected void UploadButton_Click(object sender, EventArgs e)
{
  if (FileUpload1.HasFile)
  {
     try
     {
        string filename = Path.GetFileName(FileUpload1.FileName);
        //FileUpload1 is the id of file upload control
        FileUpload1.SaveAs(@"//YourComputerName/TestFolder" + filename);
        //To show the status of File
        StatusLabel.Text = "Upload Status: File Uploaded";
     }
     catch (Exception ex)
     {
        StatusLabel.Text = ex.Message       
     }
  }
}

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License