user10608954
user10608954

Reputation:

How to make my program read a line from text file?

I am making an account checker and I have no idea how to make my program accept user input.I want user to make a .txt file under a certain name and than program should read a line from that file and use it in some areas of my program(In the code you can see where).

The program Im making is a minecraft name checker and it suppose to tell user is certain name availble or not.Previously I have searched web far and wide for the solution of my problem but with no luck :(

class Program
{
    static Regex Availability = new Regex(@"<div class=""col-lg-5 text-center my-1""><div class=""row no-gutters align-items-center""><div class=""col-sm-6 my-1""><div><strong>Status</strong></div><div>(.+?)</div></div>");

    static void Main(string[] args)
    {
        args = new[]
        {
            "https://namemc.com/search?q=(Line from txt file)"
        };

        using (var client = new WebClient())
        {
            var content = ScrubContent(client.DownloadString(args[0]));

            var available = Availability.Matches(content).Cast<Match>().Single().Groups[1];

            Console.WriteLine("The name (line from txt file) is {0}", available);
        }
    }

    static string ScrubContent(string content)
    {
        return new string(content.Where(c => c != '\n').ToArray());
    }
}

Lets say first line in our .txt file is jeans console should print

The name Jeans is Unavailable

But now for example the first line of my file is availablename9 console should print

The name availablename9 is Available

Upvotes: 0

Views: 170

Answers (2)

Joseph
Joseph

Reputation: 865

If you know the file is going to be small, there's a convenient 'File' class you can use to get all of the lines of a particular file, retrieve the first one. It would look like this:

//Make sure to add System.IO namespace, if not already present:
//using System.IO;

var file = new File.ReadLines("C:\Path\To\File.txt");
var firstLine = file.FirstOrDefault();

If the file is going to be larger, it will be more memory efficient to use a StreamReader and go through the lines 1 by 1, but this should work fine for your purposes.

Upvotes: 1

Hogan
Hogan

Reputation: 70528

 string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

FYI this is better

static string ScrubContent(string content)
{
    return content.Split('\n')[0];
}

Upvotes: 0

Related Questions