3

Please tell me how to upload the large file using SharePoint C# CSOM, Mean while i also want to update the file properties also.

File size is large more than 10MB,

SaveBinaryDirect Not applicable because need to update the file properties mean while.

FileCreationInformation Not applicable because of large file size. Please tell me how to do this.

We have activated the document id feature and also we are maintaining the file versioning. Updating file properties after uploading creating a 2nd version of file, but client don't want this to happen. So we need to update the file properties with file uploading process

4

Try to use the following code

var sourceFilePath = @"C:\Users\gremyachev\Documents\SharePoint User Guide.docx";
var targetUrl = "/Shared Documents";

using (var ctx = new ClientContext(webUri))
{
   ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);

   //Upload file
   var targetFileUrl = String.Format("{0}/{1}", targetUrl, Path.GetFileName(sourceFilePath));
   using (var fs = new FileStream(sourceFilePath, FileMode.Open))
   {
          Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx,targetFileUrl , fs, true);
   }

    //Set document properties
    var uploadedFile = ctx.Web.GetFileByServerRelativeUrl(targetFileUrl);
    var listItem = uploadedFile.ListItemAllFields;
    listItem["DocumentType"] = "Information";
    listItem.Update();
    ctx.ExecuteQuery();

}

Where you can set the properties like this listItem["DocumentType"] = "Information";

REF : For more details check update document properties in library using csom

  • i already mentioned business requirement that SaveBinaryDirect not applicable because need to update the file properties while uploading itself. – Raghavendra C Nov 3 '16 at 9:51
  • sorry for that , but you mention "Upload file to a library with properties In SharePoint C# CSOM " , "While uploading i want to update the file properties also". – Mohamed El-Qassas MVP Nov 3 '16 at 9:53
  • 2
    It's not possible to update properties while uploading the file. Approach is: upload file then update properties. @RaghavendraC – Atish Dipongkor - MVP Nov 3 '16 at 10:00
  • 2
    Above answer is doing the same, isn't it? – Atish Dipongkor - MVP Nov 3 '16 at 10:05
  • 1
    @RaghavendraC What is the exact requirement/technical blocker that forces you to update before upload vs. just after as per M.Qassas answer? – Cthulhubutt Nov 3 '16 at 10:08
4

My Senior gave a code sample from some link and this worked for my scenario. I am pasting the code sample below.

public Microsoft.SharePoint.Client.File UploadFileSlicePerSlice(ClientContext ctx, string libraryName, string fileName, int fileChunkSizeInMB = 3)
        {
            // Each sliced upload requires a unique ID.
            Guid uploadId = Guid.NewGuid();

            // Get the name of the file.
            string uniqueFileName = Path.GetFileName(fileName);

            // Ensure that target library exists, and create it if it is missing.
            if (!LibraryExists(ctx, ctx.Web, libraryName))
            {
                CreateLibrary(ctx, ctx.Web, libraryName);
            }
            // Get the folder to upload into. 
            List docs = ctx.Web.Lists.GetByTitle(libraryName);
            ctx.Load(docs, l => l.RootFolder);
            // Get the information about the folder that will hold the file.
            ctx.Load(docs.RootFolder, f => f.ServerRelativeUrl);
            ctx.ExecuteQuery();

            // File object.
            Microsoft.SharePoint.Client.File uploadFile;

            // Calculate block size in bytes.
            int blockSize = fileChunkSizeInMB * 1024 * 1024;

            // Get the information about the folder that will hold the file.
            ctx.Load(docs.RootFolder, f => f.ServerRelativeUrl);
            ctx.ExecuteQuery();


            // Get the size of the file.
            long fileSize = new FileInfo(fileName).Length;

            if (fileSize <= blockSize)
            {
                // Use regular approach.
                using (FileStream fs = new FileStream(fileName, FileMode.Open))
                {
                    FileCreationInformation fileInfo = new FileCreationInformation();
                    fileInfo.ContentStream = fs;
                    fileInfo.Url = uniqueFileName;
                    fileInfo.Overwrite = true;
                    uploadFile = docs.RootFolder.Files.Add(fileInfo);
                    ctx.Load(uploadFile);
                    ctx.ExecuteQuery();
                    // Return the file object for the uploaded file.
                    return uploadFile;
                }
            }
            else
            {
                // Use large file upload approach.
                ClientResult<long> bytesUploaded = null;

                FileStream fs = null;
                try
                {
                    fs = System.IO.File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        byte[] buffer = new byte[blockSize];
                        Byte[] lastBuffer = null;
                        long fileoffset = 0;
                        long totalBytesRead = 0;
                        int bytesRead;
                        bool first = true;
                        bool last = false;

                        // Read data from file system in blocks. 
                        while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            totalBytesRead = totalBytesRead + bytesRead;

                            // You've reached the end of the file.
                            if (totalBytesRead == fileSize)
                            {
                                last = true;
                                // Copy to a new buffer that has the correct size.
                                lastBuffer = new byte[bytesRead];
                                Array.Copy(buffer, 0, lastBuffer, 0, bytesRead);
                            }

                            if (first)
                            {
                                using (MemoryStream contentStream = new MemoryStream())
                                {
                                    // Add an empty file.
                                    FileCreationInformation fileInfo = new FileCreationInformation();
                                    fileInfo.ContentStream = contentStream;
                                    fileInfo.Url = uniqueFileName;
                                    fileInfo.Overwrite = true;
                                    uploadFile = docs.RootFolder.Files.Add(fileInfo);

                                    // Start upload by uploading the first slice. 
                                    using (MemoryStream s = new MemoryStream(buffer))
                                    {
                                        // Call the start upload method on the first slice.
                                        bytesUploaded = uploadFile.StartUpload(uploadId, s);
                                        ctx.ExecuteQuery();
                                        // fileoffset is the pointer where the next slice will be added.
                                        fileoffset = bytesUploaded.Value;
                                    }

                                    // You can only start the upload once.
                                    first = false;
                                }
                            }
                            else
                            {
                                // Get a reference to your file.
                                uploadFile = ctx.Web.GetFileByServerRelativeUrl(docs.RootFolder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + uniqueFileName);

                                if (last)
                                {
                                    // Is this the last slice of data?
                                    using (MemoryStream s = new MemoryStream(lastBuffer))
                                    {
                                        // End sliced upload by calling FinishUpload.
                                        uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s);
                                        ctx.ExecuteQuery();

                                        // Return the file object for the uploaded file.
                                        return uploadFile;
                                    }
                                }
                                else
                                {
                                    using (MemoryStream s = new MemoryStream(buffer))
                                    {
                                        // Continue sliced upload.
                                        bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s);
                                        ctx.ExecuteQuery();
                                        // Update fileoffset for the next slice.
                                        fileoffset = bytesUploaded.Value;
                                    }
                                }
                            }

                        } // while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
                    }
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Dispose();
                    }
                }
            }

            return null;
        }

This is uploading file with updating file properties

0

I was able to use what Raghavendra submitted and modified to allow placement into a folder and get setup information from Environment variables. Last but not least this works in .NET Core.

        public static async System.Threading.Tasks.Task UploadFileSlicePerSlice(string filePath, int fileChunkSizeInMB = 3)
    {

        using (ClientContext ctx = new ClientContext(AppSettings.BISharePointSite))
        {
            string account = AppSettings.SharePointAccount;
            string password = AppSettings.SharePointPassword;
            var secret = new SecureString();
            string libraryName = AppSettings.SharePointLibraryName;
            string folderName = AppSettings.SharePointFolderName;
            string dataPathInSharePoint = AppSettings.SharePointDataPath;
            ctx.Credentials = new SharePointOnlineCredentials(account, password);

            Web web = ctx.Web;
            ctx.Load(web, website => website.Lists, website => website.ServerRelativeUrl);
            await ctx.ExecuteQueryAsync();
            List list = web.Lists.GetByTitle(libraryName);
            ctx.Load(list, i => i.RootFolder.Folders, i => i.RootFolder);
            await ctx.ExecuteQueryAsync();
            var folderToBindTo = list.RootFolder.Folders;
            var folderToUpload = folderToBindTo.Where(i => i.Name == folderName).First();

            // Get the name of the file.
            string uniqueFileName = list.RootFolder.ServerRelativeUrl + dataPathInSharePoint + Path.GetFileName(filePath);

            // Each sliced upload requires a unique ID.
            Guid uploadId = Guid.NewGuid();

            // File object.
            Microsoft.SharePoint.Client.File uploadFile;

            // Calculate block size in bytes.
            int blockSize = fileChunkSizeInMB * 1024 * 1024;

            // Get the size of the file.
            long fileSize = new FileInfo(filePath).Length;

            if (fileSize <= blockSize)
            {
                // Use regular approach.
                using (FileStream fs = new FileStream(filePath, FileMode.Open))
                {

                    FileCreationInformation newFile = new FileCreationInformation();
                    newFile.ContentStream = fs;
                    newFile.Url = uniqueFileName;
                    newFile.Overwrite = true;

                    uploadFile = folderToUpload.Files.Add(newFile);
                    ctx.Load(uploadFile);
                    await ctx.ExecuteQueryAsync();
                }
            }
            else
            {
                // Use large file upload approach.
                ClientResult<long> bytesUploaded = null;

                FileStream fs = null;
                try
                {
                    fs = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        byte[] buffer = new byte[blockSize];
                        Byte[] lastBuffer = null;
                        long fileoffset = 0;
                        long totalBytesRead = 0;
                        int bytesRead;
                        bool first = true;
                        bool last = false;

                        // Read data from file system in blocks. 
                        while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            totalBytesRead = totalBytesRead + bytesRead;

                            // You've reached the end of the file.
                            if (totalBytesRead == fileSize)
                            {
                                last = true;
                                // Copy to a new buffer that has the correct size.
                                lastBuffer = new byte[bytesRead];
                                Array.Copy(buffer, 0, lastBuffer, 0, bytesRead);
                            }

                            if (first)
                            {
                                using (MemoryStream contentStream = new MemoryStream())
                                {
                                    // Add an empty file.
                                    FileCreationInformation fileInfo = new FileCreationInformation();
                                    fileInfo.ContentStream = contentStream;
                                    fileInfo.Url = uniqueFileName;
                                    fileInfo.Overwrite = true;
                                    uploadFile = list.RootFolder.Files.Add(fileInfo);

                                    // Start upload by uploading the first slice. 
                                    using (MemoryStream s = new MemoryStream(buffer))
                                    {
                                        // Call the start upload method on the first slice.
                                        bytesUploaded = uploadFile.StartUpload(uploadId, s);
                                        await ctx.ExecuteQueryAsync();
                                        // fileoffset is the pointer where the next slice will be added.
                                        fileoffset = bytesUploaded.Value;
                                    }

                                    // You can only start the upload once.
                                    first = false;
                                }
                            }
                            else
                            {
                                // Get a reference to your file.
                                uploadFile = ctx.Web.GetFileByServerRelativeUrl(uniqueFileName);

                                if (last)
                                {
                                    // Is this the last slice of data?
                                    using (MemoryStream s = new MemoryStream(lastBuffer))
                                    {
                                        // End sliced upload by calling FinishUpload.
                                        uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s);
                                        await ctx.ExecuteQueryAsync();

                                    }
                                }
                                else
                                {
                                    using (MemoryStream s = new MemoryStream(buffer))
                                    {
                                        // Continue sliced upload.
                                        bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s);
                                        await ctx.ExecuteQueryAsync();
                                        // Update fileoffset for the next slice.
                                        fileoffset = bytesUploaded.Value;
                                    }
                                }
                            }

                        } // while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
                    }
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Dispose();
                    }
                }
            }
        }

    }

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.