Skip to main content

SharePoint 2010: Attach files to List/Library using Managed Client Object Model

Client Objet Model (OM) is a great new addition in SharePoint 2010. I have discussed before how to manipulate lists and list items using Managed Object Model. Today I’ll discuss on how to attach file to list item or add file to library using Managed Client Object Model.

Upload File in Library

The following code snippet shows how to upload file in document library:
public void UploadFileInLibrary(string siteUrl, string webName, string libraryName, string subfolderPath, string fileName)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {

        string uploadLocation = Path.GetFileName(fileName);
        if (!string.IsNullOrEmpty(subfolderPath))
        {
            uploadLocation = string.Format("{0}/{1}", subfolderPath, uploadLocation);
        }
        uploadLocation = string.Format("/{0}/{1}/{2}", webName, libraryName, uploadLocation);
        var list = clientContext.Web.Lists.GetByTitle(libraryName);
        var fileCreationInformation = new FileCreationInformation();
        fileCreationInformation.Content = System.IO.File.ReadAllBytes(fileName);
        fileCreationInformation.Overwrite = true;
        fileCreationInformation.Url = uploadLocation;
        list.RootFolder.Files.Add(fileCreationInformation);
        clientContext.ExecuteQuery();
    }
}
In the above code snippet, I have constructed the full path to the update location by concatenating the subfolderpath with library location. The site url is the spsite location whereas web name is name of the web site. To upload a file I have use FileCreationInformation object which is part of Client Object Model. To use the above method you can call the method as shown below. The instance is the class instance which has the method. Here the subfolderpath is the folder location inside the library where the document will be uploaded.
Instance.UploadFileInLibrary("http://mysite","mywebname", LibraryName,"folder1/folder2", @"c:\myfiles\LibraryItem.xlsx");

 

Download File From Library

The following code snippets shows how to download file from library:
public void DownloadFileFromLibrary(string siteUrl, string webName, string libraryName, string subfolderPath, string fileName, string downloadPath)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
        string filePath = string.Empty;
        if (!string.IsNullOrEmpty(subfolderPath))
        {
            filePath = string.Format("/{0}/{1}/{2}/{3}", webName, libraryName, subfolderPath, fileName);
        }
        else
        {
            filePath = string.Format("/{0}/{1}/{2}", webName, subfolderPath, fileName);
        }

        var fileInformation = File.OpenBinaryDirect(clientContext, filePath);
        var stream = fileInformation.Stream;
        IList<byte> content = new List<byte>();
        int b;
        while ((b = fileInformation.Stream.ReadByte()) != -1)
        {
            content.Add((byte)b);
        }
        var downloadFileName = Path.Combine(downloadPath, fileName);
        System.IO.File.WriteAllBytes(downloadFileName, content.ToArray());
        fileInformation.Stream.Close();
    }
}
As above code shows, we can use Microsoft.SharePoint.Client.File.OpenBinaryDirect method to download file directly from SharePoint. However, SharePoint open the file as binary stream so you need read the full stream before processing the file. The subfolderpath is same as described in ‘Upload File in Library’ section.

Delete File From Library

The following code snippet shows how to delete file from library:
public void DeleteFileFormLibrary(string siteUrl, string webName, string listName, string subfolder, string attachmentFileName)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
        string attachmentPath = string.Empty;
        if (string.IsNullOrEmpty(subfolder))
        {
            attachmentPath = string.Format("/{0}/{1}/{2}", webName, listName, Path.GetFileName(attachmentFileName));
        }
        else
        {
            attachmentPath = string.Format("/{0}/{1}/{2}/{3}", webName, listName, subfolder, Path.GetFileName(attachmentFileName));
        }
        var file = clientContext.Web.GetFileByServerRelativeUrl(attachmentPath);
        file.DeleteObject();
        clientContext.ExecuteQuery();
    }
}
As the above code , the DeleteObject method is invoked on file object to delete the file.

Attach File to ListItem

The following code snippet shows how to attach file to list item. The attachments in list are places in a folder whose location is like “http://siteurl/lists/[listname]/Attachments/[ListItemID]/[filename]”. So I have constructed the attchment location first and use Microsoft.SharePoint.Client.File.SaveBinaryDirect method to upload the file. Here in the method, Item id is the list item id that I want to attach the file to.
public void AttachFileToListItem(string siteUrl, string webName, string listName, int itemId, string fileName, bool overwrite)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
        FileStream fileStream = new FileStream(fileName, FileMode.Open);
        string attachmentPath = string.Format("/{0}/Lists/{1}/Attachments/{2}/{3}", webName, listName, itemId, Path.GetFileName(fileName));
        File.SaveBinaryDirect(clientContext, attachmentPath, fileStream, overwrite);
    }
}

 

Download File from ListItem

The following code snippet shows how to download file that is attached with list item.
public void DownloadAttachedFileFromListItem(string siteUrl, string webName, int itemId, string attachmentName, string listName, string downloadLocation)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
        string attachmentPath = string.Format("/{0}/lists/{1}/Attachments/{2}/{3}", webName, listName, itemId, Path.GetFileName(attachmentName));
        var fileInformation = File.OpenBinaryDirect(clientContext, attachmentPath);
        IList<byte> content = new List<byte>();
        int b;
        while ((b = fileInformation.Stream.ReadByte()) != -1)
        {
            content.Add((byte)b);
        }
        var downloadFileName = Path.Combine(downloadLocation, attachmentName);
        System.IO.File.WriteAllBytes(downloadFileName, content.ToArray());
        fileInformation.Stream.Close();
    }
}
As said before, the attachment location is “http://siteurl/lists/[listname]/Attachments/[itemid]/[filename]”. So I have used Microsoft.SharePoint.Client.File.OpenBinraryDirect to download the file.

Delete Attached File From ListItem

The following code shows how to delete a file that is attached with list item.
public void DeleteAttachedFileFromListItem(string siteUrl, string webName, int itemId, string attachmentFileName, string listName)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
        //http://siteurl/lists/[listname]/attachments/[itemid]/[filename]
        string attachmentPath = string.Format("/{0}/lists/{1}/Attachments/{2}/{3}", webName, listName, itemId, Path.GetFileName(attachmentFileName));
        var file = clientContext.Web.GetFileByServerRelativeUrl(attachmentPath);
        file.DeleteObject();
        clientContext.ExecuteQuery();
    }
}

Popular posts from this blog

Migrating from Skype for Business to Microsoft Teams: A Step-by-Step Guide

Do you still use Skype for Business to meet the communication and collaboration needs of your business? If so, now is the perfect time to think about switching to Microsoft Teams, a cutting-edge platform with cutting-edge capabilities and seamless connectivity with other Microsoft services. But if you're unfamiliar with the procedure, switching to a new platform can seem like a difficult task. I'll walk you through the process of switching from Skype for Business to Microsoft Teams in this article. Plan the migration in Step 1 You must make a plan before you start the relocation procedure. Set a deadline, make a list of all the Skype for Business capabilities you presently use, and choose whether to migrate gradually or all at once. Step 2: Set up your surroundings. Make sure your network and infrastructure fulfil Microsoft Teams' standards. Upgrades to your hardware, software, and licences might be necessary. Additionally, confirm that you have the right permissions to ca

How to: Debug SharePoint Applications

You can greatly simplify debugging by using Visual Studio extensions for Windows SharePoint Services. This topic includes procedures that explain the following: Debugging with Visual Studio extensions for Windows SharePoint Services Performing manual debugging Performing remote debugging Debugging with Visual Studio extensions for Windows SharePoint Services Press the F5 key to begin debugging with Visual Studio extensions for Windows SharePoint Services. The following procedure demonstrates how to enable F5 debugging. To enable F5 debugging Locate and open the target SharePoint application's Web.config file. By default, it is located in C:\Inetpub\wwwroot\wss\VirtualDirectories\80. Find the following line of code and change the  debug  attribute to  true . Save the changes to the Web.config file. In Visual Studio, right-click the SharePoint project, and then click  Properties . Click the  Debug  tab, and then type the target SharePoint URL in t

SharePoint 2010 – How to use Audio and Video Webpart

Video and Audio Web Part [ a.k.a Media Web Part ] is one of the new cool web parts in SharePoint 2010, so in this article I am going to show you the way to add this web part in your page. To add Media web part to the page you must activate those two features 1- SharePoint Server Publishing Infrastructure Feature in Site Collection features 2- SharePoint Server Publishing Feature in Site features After that edit page then click on Insert tab in SharePoint Ribbon then select Video and Audio Now the Media Web Part in the page Click on the Media Web Part and you will find Options Tab in the Ribbon As you can see in the Options tab there are Chang Media button allow you to select the video and Chang Image button to change the image of web part and Styles (Dark, Light) Click on Change Media to select the Media file. From Computer opens up the Upload media so you can upload the video and display it. Once you click ok and saving the page. Click on play button and enj