1

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.

3
  • This will help: blogs.davelozinski.com/curiousconsultant/… Commented Mar 19, 2014 at 6:00
  • Please, do not include information about a language used in a question title unless it wouldn't make sense without it. Tags serve this purpose. Commented Mar 19, 2014 at 6:17
  • This should not be slow. Can you post your code to see what it is that's making your parsing slow? Have you measured it, and how long does it take? Commented Mar 19, 2014 at 8:47

4 Answers 4

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use ReadToEnd() if you're going to need to read all 2000+ lines. Then you can execute the line parsing in parallel.

Comments

1

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);
}

1 Comment

I am follow this technique. Is there any other way?
1

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)
    }));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.