eswar
eswar

Reputation: 1

Error while i try to read a content of a text file - 'cannot convert string to char'

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

Answers (2)

vc 74
vc 74

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

Creyke
Creyke

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

Related Questions