How to read a tab delimited file using C# VS 2005

I am a newbie to VS 2005 C#. A common task I do in other languages is the reading of tab delimited text files. For this question can you provide a small snippet of code that would illustrate how to open, read and then parse a tab delimited test file? In this case, I also then need to write to a tab delimited text file after some data manipulation. A small snippet of code to write the text data back out to a second text file would be helpful as well.

Thank you,
Who is Participating?
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
Some simple examples...

            // to read a tab delimited file...
            String fileName = @"c:\someFile.txt";
            System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
            String[] values;
            String line = sr.ReadLine();            
            while (line != null)
                values = line.Split('\t');
                // do something with "values"...

                line = sr.ReadLine();

            // to write to a file...
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName);
sorry, I'm too lazy to write the code, just do this:
open the file using TextReader, loop then read line by line using ReadLine, finish the loop at the EOF.

In the loop you have a String, loop into it searching for char 9, and thats it, use the substring for your purposes.
Anurag ThakurTechnical ManagerCommented:
i hope this helps

using System;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;

namespace ReadingFile
      /// Summary description for Class1.
      class Class1
            /// The main entry point for the application.
            static void Main(string[] args)
                  char [] temp = new char[4];
                  StreamReader sr = new StreamReader(File.OpenRead("file.txt"));
                  ArrayList myAL = new ArrayList();
                        while(sr.Peek() != -1)
                  catch(EndOfStreamException e)
                        Console.WriteLine(" the error is" + e);
                  int r =myAL.Count;
                  string[] str;
                  foreach(object o in myAL)
                        str = Regex.Split(o.ToString(), "   ");    
                        System.Collections.IEnumerator myEnumerator = str.GetEnumerator();
                        while ( myEnumerator.MoveNext() )
                              Console.Write( "\n values are " + myEnumerator.Current );


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.