Skip to main content

How to attach/delete/upload files to SharePoint List Item using Object Model

I have one requirement in which I need to develop a web part in which users can upload multiple documents to SharePoint List Item and they can see all uploaded files into data grid control, they also need facility for user to delete selected files, add new files from same control and also they can download files.

Here in this post, I am writing code for each functionality as per my requirements.

Code of Deleting attachment from SharePoint list item :


 private void DeleteAttachment(int NodeID, String strFileName)
    {
        try
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;

            SPListItem delItem = lstAudit.GetItemById(NodeID);
            SPAttachmentCollection atCol = delItem.Attachments;
            foreach (string strDelfileName in atCol)
            {
                if (strDelfileName == strFileName)
                {
                    atCol.Delete(strDelfileName);
                    delItem.Update();
                    lstAudit.Update();

                    return;
                }
            }

        }
        catch (Exception eDel)
        {
            string errDel = eDel.Message;
        }
    }



Code for Downloading attachment from SharePoint List Item :


private void DownloadAttachment(string FileName)
    {
        try
        {
            string AttachmentURL = string.Empty;
            AttachmentURL = FileName;
            string strName = AttachmentURL.Substring(AttachmentURL.LastIndexOf("/") + 1);
            string sbURL = AttachmentURL.Trim();
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
            Response.AppendHeader("Content-disposition", "attachment; filename=" + strName);
            Response.AppendHeader("Pragma", "cache");
            Response.AppendHeader("Cache-control", "private");
            Response.WriteFile(sbURL);
            Response.End();
        }
        catch (Exception eDwn)
        {
            Response.Write(eDwn.Message);
        }
    }


Code of Uploading Document to SharePoint List Item :

protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            string fileName = "";
            string strExtensionName = "";

            fileName = System.IO.Path.GetFileName(FileUpload.PostedFile.FileName);

            if (fileName != "")
            {
                strExtensionName = fileName.Substring(fileName.IndexOf(".") + 1);
                if (strExtensionName.Equals("webpart") || strExtensionName.Equals("dll") || strExtensionName.Equals("bat") || strExtensionName.Equals("exe"))
                {
                    lblMessage.Visible = true;
                    lblMessage.Text = "Invalid fileName!!";
                }
                else
                {
                    string _fileTime = DateTime.Now.ToFileTime().ToString();

                    string _fileorgPath = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);

                    if (txtFileName.Text.Trim().Length > 0)
                    {
                        fileName = fileName.Replace(fileName.Substring(fileName.LastIndexOf("\\") + 1), txtFileName.Text) + "." + strExtensionName;
                    }
                    string _newfilePath = _fileTime + "~" + fileName;

                    string tempFolder = Environment.GetEnvironmentVariable("TEMP");

                  
                    string _filepath = tempFolder + _newfilePath;
                  
                    FileUpload.PostedFile.SaveAs(_filepath);

                    AddRow(fileName, _filepath, 0, true);
                }
            }
            else
            {

                lblMessage.Visible = true;
                lblMessage.Text = "Please Selct file Name";

            }

        }
        catch (Exception Ex)
        {
            Response.Write(Ex.Message);
        }

    }

  
    protected void dgdUpload_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int recordToDelete = e.RowIndex;

        //dt = (DataTable)Page.Session["Files"];
        dt = (DataTable)ViewState["Files"];

        int cn = dt.Rows.Count;

        if (Convert.ToInt32(dt.Rows[recordToDelete].ItemArray[0]) != 0)
        {
            DeleteAttachment(Convert.ToInt32(dt.Rows[recordToDelete].ItemArray[0]), dt.Rows[recordToDelete].ItemArray[1].ToString());
        }

        dt.Rows.RemoveAt(recordToDelete);

        dt.AcceptChanges();
        //Page.Session["Files"] = dt;
        ViewState["Files"] = dt;
        dgdUpload.DataSource = dt;
        dgdUpload.DataBind();
    }
    private void AddMoreColumns()
    {

        dt = new DataTable("Files");

        dc = new DataColumn("ID", Type.GetType("System.Int16"));
        dt.Columns.Add(dc);

        dc = new DataColumn("FileName", Type.GetType("System.String"));
        dt.Columns.Add(dc);

        dc = new DataColumn("FilePath", Type.GetType("System.String"));
        dt.Columns.Add(dc);

        //Page.Session["Files"] = dt;
        ViewState["Files"] = dt;

    }
    private void AddRow(string file, string path, int ID, Boolean bolCheckForfiles)
    {

        Boolean bolAddRow = true;
        //dt = (DataTable)Page.Session["Files"];
        dt = (DataTable)ViewState["Files"];
      
        if (dt == null)
        {
            AddMoreColumns();

        }
        if (bolCheckForfiles)
        {
      
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow drExistingrow in dt.Rows)
                {

                    if (drExistingrow["FileName"].ToString() == file)
                    {
                        bolAddRow = false;
                    }
                }
            }
        }
        if (bolAddRow)
        {

            dr = dt.NewRow();



            dr["ID"] = ID;
            dr["FileName"] = file;
            dr["FilePath"] = path;



            dt.Rows.Add(dr);

            //Page.Session["Files"] = dt;
            ViewState["Files"] = dt;

            dgdUpload.DataSource = dt;

            dgdUpload.DataBind();//bind in grid

        }
        else
        {
            lblMessage.Visible = true;
            lblMessage.Text = "Same File Name already exists!!!";
        }
    }

  
  

    protected void dgdUpload_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "View")
        {
            string file = e.CommandArgument.ToString();
            DownloadAttachment(file);

        }
    }



        if (dt != null)
        {

            int _dtcnt = dt.Rows.Count;
            foreach (DataRow dr in dt.Rows)
            {

                Boolean bolAddAttachment = true;
                fileName = dr["FileName"].ToString();
                if (itmCorrectiveActionFinding.Attachments.Count > 0)
                {
                    foreach (string strAttachedname in itmCorrectiveActionFinding.Attachments)
                    {

                        if (fileName == strAttachedname)
                        {
                            bolAddAttachment = false;

                        }
                    }
                }
                if (bolAddAttachment)
                {
                    string strFilepath = dr["FilePath"].ToString();

                    StreamReader sr = new StreamReader(strFilepath);

                    Stream fStream = sr.BaseStream;

                    contents = new byte[fStream.Length];

                    fStream.Read(contents, 0, (int)fStream.Length);

                    fStream.Close();

                    itmCorrectiveActionFinding.Attachments.Add(fileName, contents);

                    itmCorrectiveActionFinding.Update();
                    lstCorrectiveActionFinding.Update();
                    SPContext.Current.Web.Update();
                    System.IO.File.Delete(strFilepath);

                }
            }
        }



Comments

Popular posts from this blog

Tab Control in Asp.Net

Scenerio: I need your help in designing tab control in   asp.net .My requirement is I need a tab control in   asp.net (C#) like  for example goto my computer ,right click c drive and select properties.we get tabs like general,security etc....... like that i need to design one tab control(no need of any rightclick) in my web page and the database table columns should come as tabs and inseide the tab data of that particular column should come.   Example:Employee master tab1:Employee name.........his name in the tab tab2:Age.............his age tab3:Address........his address   Solution:   You can do this using a simple div <style type="text/css"> .tabs         {             position: relative;             height: 20px;             margin: 0;   ...

AI and Microsoft: Revolutionizing Efficiency in Nonprofit Organizations

  How AI and Microsoft Enhance Efficiency in Nonprofit Organizations In today’s fast-paced world, nonprofit organizations face unique challenges—limited resources, increasing demands, and the constant need to do more with less. But what if technology could be the game-changer they need? In my latest research paper,  "How AI and Microsoft Enhance Efficiency in Nonprofit Organizations" , I explore how cutting-edge technologies like Artificial Intelligence (AI) and Microsoft’s innovative tools are revolutionizing the way nonprofits operate. From streamlining administrative tasks to enhancing donor engagement and optimizing resource allocation, AI and Microsoft’s solutions are empowering nonprofits to focus on what truly matters—their mission. This paper dives deep into real-world examples, practical applications, and the transformative potential of these technologies. Whether you’re a nonprofit professional, a tech enthusiast, or simply curious about the intersection of technolo...

Social tagging overview in Sharepoint 2010

A tag is a word or phrase that identifies an individual piece of information according to a set of attributes or criteria. Tags make it easy to find and share information about a specific subject or task. Social tagging helps users categorize information in ways that are meaningful to them. Social tagging can improve the quality of search results by filtering against specific tags, and it can also connect individuals who want to share information with other users who have like interests. This article describes the social tagging features in Microsoft SharePoint Server 2010. This article does not describe how to configure social tagging features. It also does not discuss how to implement social tagging features as part of an overall social media strategy for an enterprise. About using social tagging features Social tagging features help users to share information and to retrieve relevant, high-quality content more efficiently. Such sharing encourages collaboration and b...