简体   繁体   中英

Upload file to folder in sharepoint with C#

I try upload a file to folder (Not list) in sharepoint. But, when do "executeQuery()" show the error "File not found" :s

I tried many things, the last was:

string siteUrl = "https://xxx.sharepoint.com/sites/some/some2";
        //Insert Credentials
        ClientContext context = new ClientContext(siteUrl);

        SecureString passWord = new SecureString();
        foreach (var c in "MySecurityPassword.") passWord.AppendChar(c);
        context.Credentials = new SharePointOnlineCredentials("name@domain.com", passWord);
        Web site = context.Web;

        //Get the required RootFolder
        string barRootFolderRelativeUrl = "2017"; //<- existent folder
        Folder barFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl);

        //Create new subFolder to load files into
        string newFolderName = "pro" + DateTime.Now.ToString("yyyyMMddHHmm");
        barFolder.Folders.Add(newFolderName);
        barFolder.Update();

        //Add file to new Folder
        Folder currentRunFolder = site.GetFolderByServerRelativeUrl(barRootFolderRelativeUrl + "/" + newFolderName);
        FileCreationInformation newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(@p), Url = Path.GetFileName(@p), Overwrite = true };
        currentRunFolder.Files.Add(newFile);
        currentRunFolder.Update();

        context.ExecuteQuery();

        //Return the URL of the new uploaded file
        newUrl = siteUrl + barRootFolderRelativeUrl + "/" + newFolderName + "/" + Path.GetFileName(@p);

HELP :C

Well, i respond to myself:

The problem was the "url" param in

FileCreationInformation newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(@p), Url = Path.GetFileName(@p), Overwrite = true };

Need be the relative URL of site. Although is defined the complete url with " https://xxx.sharepoint.com/sites/some/some2 ", is necesary define "/sites/some/some2" as relative url in

FileCreationInformation newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(@p), Url = "/sites/some/some2/"+fileName, Overwrite = true };

and work. (Great job, microsoft ¬¬).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM