2012-08-29 102 views
0

我發現了很多關於(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中的應用程序池帳戶。我仍然不確定問題是什麼。

+1

該錯誤意味着你甚至沒有授權的請求已嘗試執行的文件移動網址;它與文件移動代碼本身無關 - 代碼甚至沒有運行。 –

+0

@AndrewBarber,我試圖用本地文件複製到我的本地C驅動器沒有運氣。 – Ammar

+1

你可以試試'System.Net.CredentialCache.DefaultNetworkCredentials' – Romoku

回答

-3

我決定嘗試新的方法和使用httpposted文件和.saveAs()描述here

相關問題