Reputation: 1402
I am reading .txt file in c#. I have one problem like my txt file contain more then 2000 lines and it will take lots of time to execute because currently i am read line by line and use sub-string function for split data. Each line contain one employee detail. In line i get data into fix position like,
Employee Name = 0 to 50 Character,
Employee Address = 51 to 200 Character,
Employee BDate = 201 to 215 Character,
Employee Gender = 216 to 220 Character
etc..
Is there any technique to read line and split it to array or something else with this field? I want to improve performance.
Upvotes: 1
Views: 128
Reputation: 4362
You can use Parallel ForEach for improve performance. Refer the below code.
public class Employee
{
public string Name { get; set; }
public string Address { get; set; }
public string DOB { get; set; }
public string Gender { get; set; }
}
var textLines = File.ReadAllLines("FileName.txt");
var employees = new List<Employee>();
Parallel.ForEach(textLines,
emp =>
employees.Add(new Employee()
{
Name = emp.Substring(51),
Address = emp.Substring(51, 150),
DOB = emp.Substring(201, 15),
Gender = emp.Substring(216, 5)
}));
Upvotes: 1
Reputation: 11238
You can use File.ReadLines
which will give you IEnumerable<string>
:
Employee[] employees = new Employee[2000];
int index = 0;
foreach (var line in File.ReadLines("data.txt"))
{
var employee = new Employee();
employee.Name = line.Substring(0,50);
employee.Address = line.Substring(51,150);
employee.BDate = line.Substring(201,15);
employee.Gender = line.Substring(216,5);
employees[index++] = employee;
}
Upvotes: 2
Reputation: 2095
You could use File.ReadAllLines():
var textLines = File.ReadAllLines();
foreach (var line in textLines)
{
var name = line.Substring(51);
var address = line.Substring(51,150);
var bdate = line.Substring(201, 15);
var gender = line.Substring(216,5);
}
Upvotes: 1
Reputation: 636
Use ReadToEnd() if you're going to need to read all 2000+ lines. Then you can execute the line parsing in parallel.
Upvotes: 1