• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4518
  • Last Modified:

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,
1 Solution
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.
Mike TomlinsonMiddle 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);
Anurag ThakurCommented:
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 );



Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now