To attach the file from Local Machine to SharePoint ListItem as an attachment, Import the System.IO namespace to use the Stream Class to read the file contents.

Use System.Web.UI.WebControls.FileUpload control is named as fileUpload in code.

Sample code for uploading the file from Local Machine to ListItem attachments as follows,

//Check the FileUpload control has the file

if (fileUpload.PostedFile != null)

{item = list.Items.Add();

item[“Title”] = fileUpload.FileName;

//Read the Contents from the file in Local machine

Stream fs = fileUpload.PostedFile.InputStream;                   

byte[] fileContents = new byte[fs.Length];

fs.Read(fileContents, 0, (int)fs.Length);

fs.Close();

// Add the file to the ListItem as an Attachment

SPAttachmentCollection attachments = item.Attachments;

string fileName = Path.GetFileName(fileUpload.PostedFile.FileName);

attachments.Add(fileName, fileContents); 

item.Update();                                           

}

Uploading File from Local Machine to SharePoint ListItem as an attachment
Tagged on:                         

4 thoughts on “Uploading File from Local Machine to SharePoint ListItem as an attachment

Leave a Reply

Your email address will not be published. Required fields are marked *