Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is my code:

string path = @"c:\temp\mytext.txt";
string[] lines = System.IO.File.ReadAllLines(path);

foreach (var line in lines)
{
    var firstValue = line.Split(new string[] { "   " }, StringSplitOptions.RemoveEmptyEntries)[0];
    Console.WriteLine(firstValue);

    System.IO.File.WriteAllLines(@"C:\temp\WriteLines.txt", firstValue);
}

I want to export my first value to a text file. How i can export it?

I get this error:

Cannot convert from 'string' to 'System.Collections.Generic.IEnumerable'

at this line

System.IO.File.WriteAllLines(@"C:\temp\WriteLines.txt", firstValue);
like image 540
user1477332 Avatar asked Dec 19 '22 19:12

user1477332


1 Answers

File.WriteAllLines takes a sequence of strings - you've only got a single string.

If you only want your file to contain that single string, just use File.WriteAllText:

File.WriteAllText(@"C:\temp\WriteLines.txt", firstValue);

However, given that you've got this in a loop it's going to keep replacing the contents of the file with the first part of each line of the input file.

If you're trying to get the first part of each line of your input file into your output file, you'd be better off with:

var query = File.ReadLines(inputFile)
                .Select(line => line.Split(new string[] { "   " },
                                           StringSplitOptions.RemoveEmptyEntries)[0]);
File.WriteAllLines(outputFile, query);

Note that with a using directive of

using System.IO;

you don't need to fully-qualify everything, so your code will be much clearer.

like image 190
Jon Skeet Avatar answered Dec 28 '22 09:12

Jon Skeet