1

I'm trying to have my web service write to a shared drive on our intranet. I'm getting an IOException on my StreamWriter

 string fullpath = path + "\\" + fileName;
 using (System.IO.StreamWriter file = new System.IO.StreamWriter(fullpath, append))
 {           
     file.WriteLine(contents);
     file.Close();
 }

And the exception I'm seeing,

IOException - Logon failure: unknown user name or bad password 

If I'm understanding correctly, the user of the IIS web server needs to have access to write to the shared drive. I'm wondering if there's a way I can hard-code credentials for now, to write to the shared drive for debugging purposes. How can I provide credentials to a StreamWriter, or is there another mechanism I should be using?

I looked into Impersonation (using StreamWriter on server in C#) and would like to use that as a last resort if possible.

Talen Kylon
  • 1,908
  • 7
  • 32
  • 60
  • is the service interacting with the file trying to access a file that it does not have file level access to? e.g. if you use the same user account, can you open the file? – Joe_DM Jul 15 '17 at 04:46
  • to clarify on above comment, the user / service account will be used to request the file, so whatever user the IIS Server is running the application pool as will need permissions to the file. If this is managed be Active Directory users and Windows Permissions, maybe have a chat to the system administrator and request these permissions? – Joe_DM Jul 15 '17 at 04:48
  • @Joe_DM Yep I figured this would need to be managed by the sys. admin. I just wanted to work on it tonight and was wondering if there were other ways to provide credentials. – Talen Kylon Jul 15 '17 at 04:55
  • I see an answer has been posted. I don't know if that will work but worth a try. You could for testing purposes set the application pool to run under your personal credentials for testing purposes... Although you should make an automatic reminder to make ensure you don't forget to set it back later and end up scratching your head when something starts working differently in local vs production – Joe_DM Jul 15 '17 at 05:05

1 Answers1

0

Whenever you write to a network drive programmatically, you use the username and password that you used to start the program with. Unless you are using a domain, this will generate an error because the network drive does not recognize your username and password.

So to fix this, all you need to do is run the same code you have as a different user. This is basically the impersonation stuff you wanted to avoid, but I found a useful Stack Overflow Thread that explains this and has links to wrapper classes you can use in your code to make things simpler.

As Simple as this (from thread):

using (Impersonation.LogonUser(domain, username, password, logonType))
{
        // do whatever you want as this user.
}

This should resolve your issue

spicy.dll
  • 948
  • 8
  • 23