.NET Impersonate not working!
- by Jagd
I have a webpage that allows a user to upload a file to a network share. When I run the webpage locally (within VS 2008) and try to upload the file, it works! However, when I deploy the website to the webserver and try to upload the file through the webpage, it doesn't work!
The error being returned to me on the webserver says "Access to the path '\05prd1\emp\test.txt' is denied. So, obviously, this is a permissions issue.
The network share is configured to allow full access both to me (NT authentication) and to the NETWORK SERVICE (which is .NET's default account and what we have set in our IIS application pool as the default user for this website).
I have tried this with and without authentication, and neither one works on the webserver, yet both ways works on my local machine.
The code that does the file upload is below. Please note that the code below includes impersonation, but like I said above, I've tried it with and without impersonation and it's made no difference.
if (fuCourses.PostedFile != null && fuCourses.PostedFile.ContentLength > 0) {
System.Security.Principal.WindowsImpersonationContext impCtx;
impCtx =
((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
try {
lblMsg.Visible = true;
// The courses file to be uploaded
HttpPostedFile file = fuCourses.PostedFile;
string fName = file.FileName;
string uploadPath = "\\\\05prd1\\emp\\";
// Get the file name
if (fName.Contains("\\")) {
fName = fName.Substring(
fName.LastIndexOf("\\") + 1);
}
// Delete the courses file if it is already on \\05prd1\emp
FileInfo fi = new FileInfo(uploadPath + fName);
if (fi != null && fi.Exists) {
fi.Delete();
}
// Open new file stream on \\05prd1\emp and read bytes into it from file upload
FileStream fs = File.Create(uploadPath + fName, file.ContentLength);
using (Stream stream = file.InputStream) {
byte[] b = new byte[4096];
int read;
while ((read = stream.Read(b, 0, b.Length)) > 0) {
fs.Write(b, 0, read);
}
}
fs.Close();
lblMsg.Text = "File Successfully Uploaded";
lblMsg.ForeColor = System.Drawing.Color.Green;
}
catch (Exception ex) {
lblMsg.Text = ex.Message;
lblMsg.ForeColor = System.Drawing.Color.Red;
}
finally {
impCtx.Undo();
}
}
Any help on this would be very appreciated!