[英]StreamWriter throws IOException Logon failure: unknown user name or bad password
I'm trying to have my web service write to a shared drive on our intranet. 我正在尝试将我的Web服务写入我们Intranet上的共享驱动器。 I'm getting an IOException on my StreamWriter 我的StreamWriter上出现IOException
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. 如果我理解正确,则IIS Web服务器的用户需要具有访问写入共享驱动器的权限。 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? 如何为StreamWriter提供凭据,或者应该使用其他机制?
I looked into Impersonation ( using StreamWriter on server in C# ) and would like to use that as a last resort if possible. 我研究了模拟( 在C#服务器上使用StreamWriter ),并希望在可能的情况下将其用作最后的手段。
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. 基本上,这是您要避免的模拟工作,但是我发现了一个有用的Stack Overflow线程 ,它对此进行了解释,并提供了指向包装器类的链接,您可以在代码中使用这些包装器类来简化事情。
As Simple as this (from thread ): 就这么简单(来自thread ):
using (Impersonation.LogonUser(domain, username, password, logonType))
{
// do whatever you want as this user.
}
This should resolve your issue 这应该可以解决您的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.