views:

918

answers:

2

How do I specify the username and password in order for my program to open a file for reading? The program that needs to access the file is running from an account that does not have read access to the folder the file is in. Program is written in C# and .NET 2, running under XP and file is on a Windows Server 2003 machine.

A: 

You can impersonate a user who has the necessary rights. There is an article on MSDN that describes how to do this.

Joe
+2  A: 

You want to impersonate a user who does have the rights to access the file.

I recommend using a class like this - http://www.codeproject.com/KB/cs/zetaimpersonator.aspx. It hides all the nasty implementation of doing impersonation.

using (new Impersonator("myUsername", "myDomainname", "myPassword"))
{
  string fileText = File.ReadAllText("c:\test.txt");
  Console.WriteLine(fileText);
}
James Newton-King
This works great. I found the file paths must be in UNC format if located on another machine.