WebClient Upload file to web
I would like to know if I code it correctly. To upload file manually to my work开发者_如何转开发place server, I have to use Login ID and Password. With the clode below, should I include my loginID and Password as well?
public void SaveLogsToWeb(string logFileName)
{
WebClient webClient = new WebClient();
string webAddress = null;
try
{
webAddress = @"http://myCompany/ShareDoc/";
webClient.Credentials = CredentialCache.DefaultCredentials;
WebRequest serverRequest = WebRequest.Create(webAddress);
WebResponse serverResponse;
serverResponse = serverRequest.GetResponse();
serverResponse.Close();
webClient.UploadFile(webAddress + logFileName, "PUT", logFileName);
webClient.Dispose();
webClient = null;
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
When I run it, exception throws "(401) Unauthorized"
thanks.
You should never include user/password information in a code file. The reason this is throwing up a 401 is because the internet user and the application pool it's running under don't have write permissions to the directory you're attempting to write to.
Right-click on the directory and add /ASPNET and /Network Service as users with write permission. This should clear up the problem. Make sure you isolate the directory.
Here's a good msdn article on it: http://support.microsoft.com/kb/815153
Very late maybe but, you can add these 2 lines before webClient.Upload..
to get it fixed:
webClient.Headers["Accept"] = "/";
webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
精彩评论