How to partially read a file with C# .NET

Say you have a large file with a lot of text in it and you need to find a particular bit. One way could be to read the entire text into memory and search through it. Another, more memory-friendly solution is to keep reading the file line by line until the search term has been found.

Suppose you have a text file with the following random English content:

Unfeeling so rapturous discovery he exquisite. Reasonably so middletons or impression by terminated. Old pleasure required removing elegance him had. Down she bore sing saw calm high. Of an or game gate west face shed. no great but music too old found arose.

Offered say visited elderly and. Waited period are played family man formed. He ye body or made on pain part meet. You one delay nor begin our folly abode. By disposed replying mr me unpacked no. As moonlight of my resolving unwilling.

Inquietude simplicity terminated she compliment remarkably few her nay. The weeks are ham asked jokes. Neglected perceived shy nay concluded. Not mile draw plan snug next all. Houses latter an valley be indeed wished merely in my. Money doubt oh drawn every or an china. Visited out friends for expense message set eat.

Also suppose that you’d like to find the first occurrence of “formed”. The following code will do just that:

private static void ReadFilePartially()
	using (StreamReader streamReader = File.OpenText(@"c:\mydirectory\source.txt"))
		String searchString = "formed";
		bool searchStringFound = false;

		while (!searchStringFound && !streamReader.EndOfStream)
			string line = streamReader.ReadLine();
			if (line.Contains(searchString))
				Console.WriteLine("Search term {0} found in the following line:\n{1}", searchString, line);
				searchStringFound = true;

Read all posts dedicated to file I/O here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

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 )

Facebook photo

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

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: