0

I am new to learning C#, and i'm attempting to create a simple console application that asks the user a set of questions, and then saves the answers into a .txt file on the desktop. However, my below code doesn't seem to work.

static void Main(string[] args)
        {
            Console.WriteLine("Enter your first name.");
            string firstName = Console.ReadLine();
            Console.WriteLine("Enter your last name.");
            string lastName = Console.ReadLine();
            Console.WriteLine("Enter your job title.");
            string jobTitle = Console.ReadLine();
            Console.WriteLine("What came first, the chicken or the egg?");
            string chickenEgg = Console.ReadLine();

            string path = @"C:\Users\njones\Desktop\NiallJones.txt";

            File.WriteAllText(path, firstName, lastName, jobTitle, chickenEgg);

            Console.WriteLine("Your information has been recorded. A copy can be found on your desktop.");
        }

I believe the problem lies around the File.WriteAllText part. Please could someone help point me in the right direction as to why this doesn't work, and what I can do in order to improve on this?

Thanks!

NiallUK
  • 97
  • 12
  • 1
    https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=netframework-4.8 shows the methods you can call. None of them take 5 parameters. Hint - create a _single_ string containing everything you want to write to the file. – mjwills Apr 08 '20 at 10:28
  • Thanks for your comment. I'll have a look into how to merge all information into 1 string! – NiallUK Apr 08 '20 at 10:30

2 Answers2

2

Always check the documentation of the function you are trying to use.

public static void WriteAllText (string path, string contents);

As you can see, there is two parameter that can go into this function.

To write to the file you'll need to compose a single string (the content). The string type in c# has a operator overload (+) to put string together.

File.WriteAllText(path, firstName+lastName+jobTitle+chickenEgg);

But you will be disapointed when you will read the file it will look like: "NameLastNameJobTitleChickenOrEgg"

So i'd reccomend you put a delimiter between your fields so you can decompose your string with the String.split() function and get individual fields.

Your goal output would be something like: "Name;LastName;JobTitle;ChickenOrEgg"

Danys Chalifour
  • 322
  • 1
  • 5
  • 12
1
File.WriteAllText(path, firstName + " " + lastName + " " + jobTitle + " " + chickenEgg );
Sandris B
  • 133
  • 6