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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With