Can not read from the text file specified in

I’m trying to read a text file in my C# console application, however it doesn’t read from the text file specified in, how can I fix it?

My code:

string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); if (File.Exists(docPath)) {    string text = File.ReadAllText("token.txt");    Console.WriteLine(text); } else {    Console.ForegroundColor = ConsoleColor.Magenta;    Console.WriteLine("Enter your token:");    string token = Console.ReadLine();     using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "token.txt")))    {       outputFile.Write(token);    } } 

Instead of checking the contents of token.txt in the user documents, it just prompts the user to enter their token every time, which would get very annoying for the user.

What should I do to fix this?

Asked on August 31, 2020 in .NET,
Add Comment
1 Answer(s)

The problem here is that your docPath variable doesn’t hold the path to a single file, but instead the path of a folder. (C:\{User}\Documents)

So the File.Exists check will always fail, because you’re targeting the folder. Try combining your docPath with the actual file name and it should work.

Answered on August 31, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.