Working with delimited text file

started working with a text file indicated by a pipe delimiter, and pipe - | _ | tried the following code. We do not get the desired result. separation condition must be changed, but how. Please advise. Thanks to everyone - now it works.

class Program { static void Main(string[] args) { string filePath = @"J:\dot\emp.dat"; var query = from line in File.ReadLines(filePath) let empRecord = line.Split(new string[] {"|_|"},StringSplitOptions.None) select new datFile() { name = empRecord[0], employeeid = empRecord[1], income = empRecord[2], expenses = empRecord[3] }; foreach (var item in query) { Console.WriteLine(item.name, item.employeeid, item.income, item.expenses); } Console.ReadLine(); } public class datFile { public string name { get; set; } public string employeeid { get; set; } public string income { get; set; } public string expenses { get; set; } } } 

File contents:

 name|_|employeeid|_|income|_|expenses emp1|_|201501|_|100000|_|50000 emp2|_|20000|_|90000|_|30000 emp3|_|34234|_|100000|_|23000 

Conclusion:

  name emp1 emp3 emp3 ----- 
+6
source share
4 answers

The problem is actually here:

 Console.WriteLine(item.name, item.employeeid, item.income, item.expenses); 

Using item.name as a format string that does not include {0} , {1} or {2} , so the rest of the arguments are useless. Try this, which indicates the format string, and then the values ​​to fill in:

 Console.WriteLine("{0} {1} {2} {3}", item.name, item.employeeid, item.income, item.expenses); 
+16
source

Have you tried splitting with char [] instead of string []?

 let empRecord = line.Split(new char[] {'|', '_', '|'}); 
0
source

I don't work very much with console applications, but try changing the code as follows:

 foreach (var item in query) { Console.WriteLine("{0}, {1}, {2}, {3}", item.name, item.employeeid, item.income, item.expenses); } 
0
source

I am ashamed to say that I had to check it quite a bit in order to understand what was wrong, but that was because something was not so obvious.

Everything in this example is correct except this line:

 Console.WriteLine(item.name, item.employeeid, item.income, item.expenses); 

Try:

 Console.WriteLine("name={0}, employeeid={1}, income={2}, expenses={3}", item.name, item.employeeid, item.income, item.expenses); 
0
source

Source: https://habr.com/ru/post/894864/


All Articles