Reputation: 1
I have to read a text file (it contains 5 records), but get an error that I cannot convert string
to char
at Environment.NewLine. I have to read a particular line. I want to use for loop instead of foreach.
Would you please give me a hint how to solve this error?
using System;
using System.IO;
public class Example
{
public static void Main()
{
string fileName = @"C:\some\path\file.txt";
string text = File.ReadAllText(fileName);
string[] lines = text.Split(Environment.NewLine);
foreach (string line in lines) {
Console.WriteLine(line);
}
}
Upvotes: 0
Views: 218
Reputation: 38179
You can use ReadLines in this case:
IEnumerable<string> lines = File.ReadLines(fileName);
foreach (string line in lines) {
Console.WriteLine(line);
}
Upvotes: 1
Reputation: 2107
There is no overload for Split()
which takes a string
as an argument.
However there is one that takes an array of string
with a second argument of StringSplitOptions
.
Try this:
string[] lines = text.Split(new [] { Environment.NewLine }, StringSplitOptions.None);
Upvotes: 0