How to present credentials in order to open file?

21,947

Solution 1

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);
}

Solution 2

I have used the Nuget package NuGet Gallery | Simple Impersonation Library 1.1.0 but there are others; search on Impersonation for the others.

Example usage using the interactive login to work with file structures:

using (Impersonation.LogonUser("{domain}",
                               "{UserName}", 
                               "{Password}", 
                               LogonType.Interactive))
{
     var directory = @"\\MyCorpServer.net\alpha\cars";

     Assert.IsTrue(Directory.Exists(directory));
}

James' answer below was before Nuget and before he would later have the most downloaded package on Nuget. Ironic eh?

Share:
21,947
Admin
Author by

Admin

Updated on July 05, 2020

Comments

  • Admin
    Admin almost 4 years

    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.

  • Admin
    Admin over 15 years
    This works great. I found the file paths must be in UNC format if located on another machine.
  • user254875486
    user254875486 about 12 years
    Works for me too, took me a while get it to work because I missed the remark made on the referenced page: Please note: The user context that initiates the impersonation (i.e. not the user context to which it is switched to) needs to have the "Act as part of operating system" privilege set.
  • ΩmegaMan
    ΩmegaMan about 8 years
    It's a shame that the codeproject's author never moved it into Nuget. My answer's commentary was only meant for fun; for it is understood that you answered this 8 years ago before Nuget.