“尝试上传文件时,远程服务器返回错误:(401)Unauthorized”错误

时间:2012-08-29 21:40:45

标签: c# asp.net sharepoint put http-status-code-401

我发现很多关于(401)未经授权的错误的问题,但他们都没有向我解释如何诊断问题。

我创建了一个新的MVC ASP.net应用程序,以了解如何将文件上传到sharepoint文件夹。截至目前,我似乎无法复制文件 C:\ testfolder \ file.txt到 C:\ testfolder \ UPLOADEDFILES

以下是我在源文件路径和目标文件夹中发送的方法:

 //Flag to indicate whether file was uploaded successfuly or not
        bool isUploaded = true;
        try
        {
            // Create a PUT Web request to upload the file.
            WebRequest request = WebRequest.Create(targetDocumentLibraryPath);

            //Set credentials of the current security context
            request.PreAuthenticate = true;
            request.UseDefaultCredentials = true;
            ICredentials credentials = new NetworkCredential( "Username", "password", "Domain"); //I used my username and password here
            request.Credentials = credentials;
            //request.Credentials = CredentialCache.DefaultCredentials;
            request.Method = "PUT";

            // Create buffer to transfer file
            byte[] fileBuffer = new byte[1024];

            // Write the contents of the local file to the request stream.
            using (Stream stream = request.GetRequestStream())
            {
                //Load the content from local file to stream
                using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
                {
                    //Get the start point
                    int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
                    for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
                    {
                        stream.Write(fileBuffer, 0, i);
                    }

                }
            }

            // Perform the PUT request
            WebResponse response = request.GetResponse();

            //Close response
            response.Close();
        }
        catch (Exception ex)
        {
            //Set the flag to indiacte failure in uploading
            isUploaded = false; //The remote server returned an error: (401) Unauthorized.
        }

        //Return the final upload status
        return isUploaded; 
    }

我尝试了以下内容:

  • 更改文件夹的权限,以便能够为所有用户写入/读取这些文件夹。
  • 使用其他文件夹位置(SharePoint,本地驱动器,网络驱动器)将文件上传到。

有关如何解决此问题的任何想法?任何有关如何调试问题的预期也值得赞赏。

更新:可能是我的帐户被设置为IIS中的应用程序池帐户。我仍然不确定问题是什么。

2 个答案:

答案 0 :(得分:1)

这不会像代理设置那样吗?

您是否需要将默认代理设置添加到

WebRequest 

您还需要添加

<system.net> 
  <defaultProxy useDefaultCredentials="true" /> 
</system.net> 

到您的网络配置?

这可能会有所帮助。

How should I set the default proxy to use default credentials?

答案 1 :(得分:-3)

我决定尝试另一种方法并使用httpsos文件和.saveAs()描述here