In server-side object module i use this code to create a file at a destination folder:-

ListItem templetefile = null;
foreach (ListItem i in template)
templetefile = i;
byte[] fileBytes = templetefile.File.OpenBinary();
string destUrl = properties.Web.ServerRelativeUrl + "/" + shareddocsList.RootFolder.Url + "/" +
                 formattedID + "/1. Order Draft/" + formattedID + " - " + customernamelabel + " - "    + titlewithoutspecialchar.Trim() + ".xlsx";
SPFile destFile = shareddocsList.RootFolder.Files.Add(destUrl, fileBytes, false);

but inside CSOM we need to use the followinf code:-

FileCreationInformation fci = new FileCreationInformation();
fci.Overwrite = false;
fci.Url = destUrl;
fci.ContentStream = fs;
Microsoft.SharePoint.Client.File destFile = currentDL.RootFolder.Files.Add(fci);

but i am not sure if the FileCreationInformation.Url should contain the file extension and file name as in the server-side object module case?


You can use the following code to set the Url property.

//System.IO.Path.GetFileName returns the file name and extension of the specified file from given path
fci.Url = System.IO.Path.GetFileName(filePath);

Basically, you are already loading the folders where you want to add the file, so it would be okay if you just set the URL to the name of the file.

string fileName = @"C:\mydir\myfile.xlsx";
//Following would return myfile.xlsx
string onlyFileName = System.IO.Path.GetFileName(fileName);

// Get the folder to upload into.
List shareddocsList = ctx.Web.Lists.GetByTitle(libraryName);
ctx.Load(shareddocsList, l => l.RootFolder);
// Get the information about the folder that will hold the file.
ctx.Load(shareddocsList.RootFolder, f => f.ServerRelativeUrl);

Now, upload the file

// File object.
Microsoft.SharePoint.Client.File destFile = null;

using (FileStream fs = new FileStream(fileName, FileMode.Open))
    FileCreationInformation fci  = new FileCreationInformation();
    fci.ContentStream = fs;
    fci.Url = onlyFileName;
    fci.Overwrite = true;
    destFile = shareddocsList.RootFolder.Files.Add(fci);

    // Return the file object for the uploaded file.
    return uploadFile;

Check this article from Microsoft for more details about file upload to SharePoint.

Let me know if this helps.

  • but inisde the using (FileStream fs = new FileStream(filePath, FileMode.Open)) i need to pass the path of the file and not the file name,, is this correct? – John John May 12 '20 at 9:51
  • Yes, you are correct, in "new FileStream" you have to pass the full path of your local file. – UBK May 12 '20 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.