We help IT Professionals succeed at work.
Get Started

Webapp showing files on fileshare with impersonation

Last Modified: 2013-11-08

I have a webapp that shows files from a fileshare. The authenticated windows user has permissions to read from the share, but the ASP.NET process hasn't. So I have this code with impersonation which works on my development environment. But in production environment it doesn't. Looking in the security event viewer on the fileserver I can see that it is the ANONYMOUS LOGON account which logs on to the fileserver.

Can you spot where I go wrong or perhaps suggest an alternative solution. Mind you, I can't change permissions on the share.



WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
WindowsImpersonationContext ctx = null;
try {
// Start impersonating.
	ctx = winId.Impersonate();
// Now impersonating.
// Access resources using the identity of the authenticated user.
	FileStream fs = new FileStream(uri, FileMode.Open, FileAccess.Read, FileShare.Read);
	Response.ContentType = "application/pdf";

	byte[] buf = new byte[1024];
	int i;
	while ((i = fs .Read(buf, 0, buf.Length)) > 0) Response.OutputStream.Write(buf, 0, i);
} catch (Exception ex) {
// Prevent exceptions from propagating.
} finally {
// Revert impersonation.
	if (ctx != null) ctx.Undo();
// Back to running under the default ASP.NET process identity.

Open in new window

Watch Question
Top Expert 2010
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE