Home > Back-end >  Can someone please confirm the reason behind foreach loop giving error as "invalid token"
Can someone please confirm the reason behind foreach loop giving error as "invalid token"

Time:04-02

    string[] splittedText = File.ReadAllLines(@"file.txt");//.Split(',');

    foreach (string data in splittedText)
    {
    }

I want to read through a file in c# which returns array of string type. Then, I will be iterating over the array to fetch my desired data.

CodePudding user response:

If you want to read a CSV file, you should use a CVS parser. Values in the CSV file are separated using command and in some cases, the value in the CSV file can also contain a comma. In that case, the column values are wrapped in double-quotes. And this solution will not handle that scenario.

var splittedText = File.ReadAllText("E:\\Test.txt").Split(',');

foreach (string data in splittedText)
{
    Console.WriteLine(data.Trim());
}

CodePudding user response:

You need change File.ReadAllLines to File.ReadAllText(path) then you can split method.

  • Related