user1994100
user1994100

Reputation: 601

Assign line in text file to a string

I'm making a simple text adventure in C# and I was wondering if it was possible to read certain lines from a .txt file and assign them to a string.

I am aware of how to read all the text from a .txt file but how exactly would I assign the contents of certain lines to a string?

Upvotes: 0

Views: 2325

Answers (5)

joppiesaus
joppiesaus

Reputation: 5760

Here's a example how you can assign the lines to a string, you can't decide which line is which via fields, you have to select them yourself. which is the line of the string you want to assign. For example, you want line one, you define which as one and not zero, you want line eight, you define which with eight.

string getWord(int which)
{
    string readed = "";
    using (Systen.IO.StreamReader read = new System.IO.StreamReader("PATH HERE"))
    {
       readed = read.ReadToEnd(); 
    }
    string[] toReturn = readed.Split('\n');
    return toReturn[which - 1];
}

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460148

Probably the easiest (and cheapest in terms of memory consumption) is File.ReadLines:

String stringAtLine10 = File.ReadLines(path).ElementAtOrDefault(9);

Note that it is null if there are less than 10 lines in the file. See: ElementAtOrDefault.

It's just the concise version of a StreamReader and a counter variable which increases on every line.

Upvotes: 1

loxxy
loxxy

Reputation: 13151

Have you considered the ReadAllLines method?

It returns an array of lines from which you can choose your desired line.

So for eg, if you wish to choose the 3rd line (Assuming you have 3 lines in the file):

string[] lines = File.ReadAllLines(path);

string myThirdLine= lines[2];

Upvotes: 2

Anirudha
Anirudha

Reputation: 32797

In case you don't want to load all lines atonce

using(StreamReader reader=new StreamReader(path))
{
String line;
while((line=reader.ReadLine())!=null)//process temp
}

Upvotes: 0

xanatos
xanatos

Reputation: 111870

As an advanced alternative: ReadLines plus some LINQ:

var lines = File.ReadLines(myFilePath).Where(MyCondition).ToArray();

where MyCondition:

bool MyCondition(string line)
{
   if (line == "something")
   {
       return true;
   }

   return false;
}

Upvotes: 0

Related Questions