C# sharepoint 上传文件

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string strUserName = "123123312312";
            string fileUrl = "D:/build/1/msssql.jar";
             byte[] fileArray= AuthGetFileData(fileUrl);
            string fileName = "ss.doc";
            string targetFolder = "Shared Documents/General";
            string strPassword = "234123123";
            SecureString ssPwd = new SecureString();
            strPassword.ToList().ForEach(ssPwd.AppendChar);
            SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(strUserName, ssPwd);
            ClientContext context = new ClientContext("https://aiqweqwem.sharepoint.com/sites/IRqweqweqweqweata");
            context.Credentials = credentials;
            context.ExecuteQuery();
            UploadFile(context, targetFolder, fileName, fileArray);

            Web web = context.Web;

            context.Load(web);

            context.ExecuteQuery();

            Console.WriteLine(web.Title);
            Console.ReadKey();

        }
        public static void UploadFile(ClientContext context, string targetFolder, string fileName, byte[] fileArray)
        {
     
            Web web = context.Web;
           
            Folder docSetFolder = web.GetFolderByServerRelativeUrl(targetFolder);
            context.Load(docSetFolder);
            context.ExecuteQuery();
            string documentUrl = targetFolder + "/" + fileName;
            FileCreationInformation fci = new FileCreationInformation();
            fci.Url = documentUrl;
            fci.Content = fileArray; //byte[] take your stream and convert to byte array
            //get the folder's file collection
            FileCollection documentFiles = docSetFolder.Files;
            context.Load(documentFiles);
            context.ExecuteQuery();
            File newFile = documentFiles.Add(fci);
            context.Load(newFile);
            ListItem item = newFile.ListItemAllFields;
            context.Load(item);
            //start setting metadata here
            string contentTypeId = string.Empty;
            item["ContentTypeId"] = contentTypeId;
            item.Update();
            context.ExecuteQuery();



        }
  

    }
}

 

posted @ 2020-12-31 10:42  大哥超帅  阅读(805)  评论(0编辑  收藏  举报