-2

I have a text file having some information in the form a table, having some imporatant data at a specific column. I need to read the text file and split the files into several files based on the value in the column.
Example:

ID   Course  Name  
001  EEE     Harsha  
002  CSE     Madhuri 
003  EIE     Jagan   
004  EEE     Chandu 
005  CSE     Sukanya    
006  EIE     Sarat   

Here in this example based on course column, I can split the data into 3 files. I have to develop a similar kind of application. Please give an idea on how to approach at the solution. Thanks in advance.

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
Harsha V Chunduri
  • 394
  • 1
  • 4
  • 17
  • 2
    Step #1 - try something and post your code. – Karl Anderson Nov 13 '13 at 17:08
  • 2
    There are literally hundreds of examples of parsing out text files. Try something first, then come back with a question about code you've actually written. – tnw Nov 13 '13 at 17:10

2 Answers2

2
StreamReader fileI = new StreamReader("C:\\Users\\Harsha\\Desktop\\SampleInput.txt");
        StreamWriter fileA = new StreamWriter("C:\\Users\\Harsha\\Desktop\\A.txt", true);
        StreamWriter fileB = new StreamWriter("C:\\Users\\Harsha\\Desktop\\B.txt", true);
        StreamWriter fileC = new StreamWriter("C:\\Users\\Harsha\\Desktop\\C.txt", true);


        string line;
        int counter = System.IO.File.ReadAllLines("C:\\Users\\Harsha\\Desktop\\SampleInput.txt").Length;

        for (int linenum = 0; linenum <= counter; linenum++)
        {
            if ((line = fileI.ReadLine()) != null)
            {
                string c1 = (line.ElementAt<char>(6)).ToString();
                string c2 = (line.ElementAt<char>(7)).ToString();
                string c3 = (line.ElementAt<char>(8)).ToString();
                string c4 = c1 + c2 + c3;

                if (c4 == "CSE")
                {

                        fileA.WriteLine(line);
                }
                else if(c4=="EEE")
                {
                        fileB.WriteLine(line);
                }
                else if(c4=="EIE")
                {
                    fileC.WriteLine(line);
                }

            }
        }


        fileI.Close();
        fileA.Close();
        fileB.Close();
        fileC.Close();
Harsha V Chunduri
  • 394
  • 1
  • 4
  • 17
0

Your problem can be solved in basicly three parts:

  1. Read a textfile. Hint:

    System.IO.StreamReader file = new System.IO.StreamReader("c:\test.txt"); while((line = file.ReadLine()) != null) { .. magic stuff }

  2. Split the lines by using string.split()

  3. Write into Textfile using StreamWriter

This answer should contain more than enough "buzzwords" to solve your problems. Don't expect a complete solution here. If you got stuck at one of those steps. Post your code and we are glad to help.

Ole Albers
  • 8,715
  • 10
  • 73
  • 166