Search code examples
c#streamreader

I need to return a line of string to the user from a text file in C#


public class QuoteGenerator
{
    public static randomQuote()
    {
        string t = "Quotes.txt";
        List<string> Quotes = new List<string>();
        using (StreamReader quoteReader = new StreamReader(t))
        {
            string line = "";
            while ((line = quoteReader.ReadLine()) != null)
            {
                Quotes.Add(line);
            }
        }
        string[] response = Quotes.ToArray();
        string[] shuffle = Classes.RandomStringArrayTool.RandomizeStrings(response);

        return (shuffle[0]);
    }
}

Here's what's working and I thought my StreamReader code above would work the same:

    public string randomQuote()
    {
        string[] response = new string[] {"The fortune you seek, is in another bot"
            , "Someone has Googled you recently"
            , "This fortune no good. Try another"
            , "404 fortune not found"};
        string[] shuffle = Classes.RandomStringArrayTool.RandomizeStrings(response);
        return shuffle[0];
    }

I need to return the first line of quote from the StreamReader Method, how come the code I put together doesn't seem to work? I've thought about hard-coding the quotes but maybe it's a good idea to save them in a text file. I guess I don't understand how using StreamReader work. Can anyone please explain, I've only been coding since July. Thank you!


Solution

  • Assuming your Quotes.txt file is in the bin directory the StreamReader code works fine. The only thing obvious is that you are not specifying a return type for the randomQuote method.

    public static string randomQuote()