6

In my application I use FileStream to read from a file, that is on the fileshare somewhere in the network. So my remoteFilePath variable is something like: \\computername\folder\file.pdf

FileStream fileStream = new FileStream(remoteFilePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024 * 1024)

Unfortunately, the user that I'm running this application with (that I'm logged into the PC with) does not have access to this fileshare. I have another user (domain, login & password), that has access to those files.

Is it possible to use the other user credentials to get a file to filestream? Can I impersonate the user only to get a file, and then continue with my own user?

Tschareck
  • 4,071
  • 9
  • 47
  • 74
  • Similar thread - http://stackoverflow.com/questions/295538/how-to-provide-user-name-and-password-when-connecting-to-a-network-share – KV Prajapati Aug 17 '12 at 08:04
  • 1
    It seems like this is all you need: http://msdn.microsoft.com/en-us/library/w070t6ka(v=vs.100).aspx – Icarus Aug 17 '12 at 08:12
  • Refer http://stackoverflow.com/questions/295538/how-to-provide-user-name-and-password-when-connecting-to-a-network-share/1197430#1197430 – LCJ Feb 04 '13 at 09:34
  • 1
    Much as I hate to post a link http://platinumdogs.wordpress.com/2008/10/30/net-c-impersonation-with-network-credentials/ Has a great bit of code to use. – BugFinder Aug 17 '12 at 08:07

2 Answers2

7

Thank you for your answers. Since the share was in another domain, it was not so easy to impersonate.

I found another, easier solution. I mapped a network drive, and checked the option Connect using different credentials. Then I connect to this drive instead of the remote path.

string mappedFilePath = filePath.Replace(@"\\computername\", @"Y:\")

and use this new string in FileStream constructor.

Tschareck
  • 4,071
  • 9
  • 47
  • 74
1

You should use impersonation. More info at http://msdn.microsoft.com/en-us/library/w070t6ka.aspx

Cybermaxs
  • 24,378
  • 8
  • 83
  • 112