Search in a file and write the matched content to another file

128 views Asked by At

I have a large txt file and want to search through it and output certain strings, for example, let's say two lines are:

oNetwork.MapNetworkDrive "Q:", xyz & "\one\two\three\four"
oNetwork.MapNetworkDrive "G:", zzz

From this I'd like to copy and output the Q:, G:, and the "\one\two\three\four" to another file.

What's the most efficient way of doing this?

1

There are 1 answers

0
Tim Copenhaver On

There is ultimately only one way to read a text file. You're going to have to go line-by-line and parse the entire file to pick out the pieces you care about.

Your best bet is to read the file using a StreanReader (File.OpenText is a good way to get one). From there, just keep calling ReadLine and picking out the bits you care about.

The main way to increase efficiency is to make sure you only have to parse the file once. Save everything you care about, and only what you care about. As much as you can, act on the information in the file right away then throw it away - the less you have to store, the better. Do not use File.ReadAllText since it will read the entirety of the file into memory all at once.