我发现了很多关于 (401) Unauthorized error 的问题,但没有一个向我解释如何诊断问题。
我创建了一个新的 MVC ASP.net 应用程序来学习如何将文件上传到共享点文件夹。截至目前,我似乎无法将文件从 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 中的应用程序池帐户。我仍然不确定问题是什么。