C# Reading content from text files

This is something I do frequently, and I always forget the streaming syntax, so here it is. There are couple of ways to do this. Firstly, from an application:

  1. From the properties panel, set the Build Action as Resource and the Copy to Output Directory as Copy Always
  2. From code this can then be accessed with:
public class ListOfStrings: List
{
//@ctor
public ListOfStrings()
{
string line;

StreamResourceInfo sri = App.GetResourceStream(new Uri("Namespace;component/filename.txt", UriKind.Relative));
using (TextReader tr = new StreamReader(sri.Stream))
{
while ((line = tr.ReadLine()) != null)
{
Add(tr.ReadLine());
}
}
}
}

NOTE: Namespace;component/filename.txt: the Namespace and filename have to be replaced. Leave in the component syntax

In a class library, it is slightly different.

  1. From the properties panel, set the Build Action as Embedded Resource
  2. From code this can then be accessed with:

public class ListOfStrings: List
{
//@ctor
public ListOfStrings()
{
string line;

Assembly assembly = Assembly.GetExecutingAssembly();
Stream stream = assembly.GetManifestResourceStream("Namespace.ResourceFolder.Filename.txt");

using (TextReader tr = new StreamReader(stream))
{
while ((line = tr.ReadLine()) != null)
{
Add(tr.ReadLine());
}
}
}
}

 
NOTE: Namespace.ResourceFolder. has to be replaced with a suitable value.

Obviously, both examples return at list of string objects, one object per line.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

A WordPress.com Website.

Up ↑

%d bloggers like this: