Reading a text file from SharePoint Document Library

Was asked to set up a quick text file import into a list – I needed somewhere to shove the test text file so I put it into a Document Library and then realised I needed to be able to read it from there.  Simple, once you know how.

The key thing to remember is that you pull the file using its full URL, so http://mysite/mysubsite/library/folder/document.txt is required rather than grabbing the Document Library and

var debugText = new List<string>();
string url="http://mysite/mysubsite";
string docLibrary = "Shared Documents";
string fileName = "mytextfile.txt";
using (var site = new SPSite(SPContext.Current.Site.Url))
  using (var web = site.RootWeb)
    var targetFile = String.Format("{0}/{1}/{2}", url, docLibrary, fileName);
    SPFile file = web.GetFile(targetFile);                                           
    StreamReader reader = new StreamReader(file.OpenBinaryStream());
    while (!reader.EndOfStream)
      var line = reader.ReadLine();
      //do stuff

Hat tip: Gitolekha


Posted on November 30, 2012, in SharePoint. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: