Pages

Subscribe:

Sunday, October 30, 2011

Read a file in Sharepoint document library


The below Code snippet might be helpful when you want to read a text file or a csv file that you uploaded in your document library via code.
I had a csv file with three columns; and I wanted to extract the data and add them into a list as an new item.
Code : The code reads each line of the csv file and then split the entries(columns) by “,” . If you have a text file then you can either split by space or by characters whatever is your requirement.
string line;
StreamReader file;
string contents = string.Empty;
SPFile spfile = properties.ListItem.File;
if (spfile.Exists)
{
string filePath = oWeb.Url + spfile.ServerRelativeUrl; -> oWeb is SPWeb instance
file = new StreamReader(spfile.OpenBinaryStream());
while ((line = file.ReadLine()) != null) -> Reading line by line of the csv file
{
char[] splitter = { ‘,’ };
String[] Array = line.ToString().Split(splitter);
// Now my Array has all the columns of the first line. I then added it to a new list as an item
using (SPSite oSiteCollection = new SPSite(SiteID))
{
using (SPWeb oWeb = oSiteCollection.OpenWeb(WebID))
{
SPList myList = oWeb.Lists["My Custom List"];
SPItem newEntry = myList.Items.Add();
newEntry["Col1"] = Array[0];
newEntry["Col2"] = Array[1];
newEntry["Col3"] = Array[2];
newEntry.Update();
myList.Update();
}}

No comments:

Post a Comment