cannot convert from 'string' to 'System.Collections.Generic.IEnumerable<string>'

Viewed 515

I am testing and learning about System.IO in c#, in my program I ask the user for some text to write in a file, store it, and then use File.WriteAllLines() to write them in a file. This however shows a error saying :

Argument 2: cannot convert from 'string' to 'System.Collections.Generic.IEnumerable'

Here is my code:

Console.WriteLine("Write Some text");
string text = Console.ReadLine();
File.WriteAllLines("Text.txt" , text);
1 Answers

You probably want File.WriteAllText("Text.txt", text); which takes a single string value:

Console.WriteLine("Write Some text");
string text = Console.ReadLine();
File.WriteAllText("Text.txt" , text);

The error is telling you that File.WriteAllLines expects the text variable to be some kind of collection of string (e.g. an array, list, etc.) that it can iterate through. As you have a single string, this won't work.

Alternatively, if you plan to read many lines from the Console and write them at once, you could generate a list:

List<string> lines = new List<string>();
for (int i = 0; i < 5; ++i) // repeat 5x
{
    // read a line from the console and add it to the list
    lines.Add(Console.ReadLine());
}
File.WriteAllLines("Text.txt", lines);

Now WriteAllLines will work because List<string> implements IEnumerable<string>.

Documentation:

Related