开发者

WebClient Upload file to web

开发者 https://www.devze.com 2022-12-16 16:29 出处:网络
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 P

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;)");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号