我使用字节[]中的C#代码将文件上传到Sharpoint。
代码提供以下错误:
访问被拒绝。您无权执行此操作或访问此资源
我可以登录SP并打包并上传文件。我检查过它是相同的用户ID,它具有权限或创建列表,添加文档,完全控制和使用远程接口。
public static bool UploadFile(SP sp, string folderName, string fileNameWithExtension, byte[] fileContent, TraceWriter log)
{
bool result = false;
try
{
SecureString securePwd = new SecureString();
char[] pwdarray = sp.pwd.ToCharArray();
foreach (var item in pwdarray)
{
securePwd.AppendChar(item);
}
SharePointOnlineCredentials creds = new SharePointOnlineCredentials(sp.id, securePwd);
using (ClientContext clientContext = new ClientContext(sp.url))
{
clientContext.Credentials = creds;
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
Web web = clientContext.Web;
var fileCreationInformation = new FileCreationInformation();
fileCreationInformation.Content = fileContent;
fileCreationInformation.Overwrite = true;
fileCreationInformation.Url = fileNameWithExtension;
Microsoft.SharePoint.Client.List docs = web.Lists.GetByTitle("FtpFiles");
docs.RootFolder.Folders.Add(folderName);
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(fileCreationInformation);
clientContext.ExecuteQuery();
return result = true;
}
}
catch (Exception ex)
{
throw ex;
}
}
请指导我不要弄错:(
答案 0 :(得分:0)
这是一个供您参考的演示,我已成功测试过。
/// <summary>
/// upload file to Document Library
/// </summary>
/// <param name="context"></param>
/// <param name="documentLibraryName"></param>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
public static void uploadFileToDocLib(ClientContext context, string documentLibraryName, string filePath,string fileName)
{
string siteURL = context.Url.EndsWith("/") ? context.Url.Substring(0, context.Url.Length - 1) : context.Url;
List list = context.Web.Lists.GetByTitle(documentLibraryName);
context.Load(list);
context.ExecuteQuery();
FileStream fileStream = new FileStream(filePath, FileMode.Open);
FileCreationInformation newFileInfo = new FileCreationInformation()
{
ContentStream = fileStream,
Url = siteURL + "/" + documentLibraryName + "/" + fileName,
Overwrite = true
};
Microsoft.SharePoint.Client.File file = list.RootFolder.Files.Add(newFileInfo);
context.Load(file);
context.ExecuteQuery();
}
设置SharePoint Online的凭据
/// <summary>
/// Set credential of SharePoint Online
/// </summary>
/// <param name="clientContext"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
public static void setOnlineCredential(ClientContext clientContext,string userName,string password)
{
//set the user name and password
SecureString secureString = new SecureString();
foreach (char c in password.ToCharArray())
{
secureString.AppendChar(c);
}
clientContext.Credentials = new SharePointOnlineCredentials(userName, secureString);
}