Solved

reading tab-separated files in C#

Posted on 2006-07-11
2
1,606 Views
Last Modified: 2008-01-09
Is there a function in C# that reads tab- (or comma-) separated textfiles? For those of you who's familiar with Matlab, what I need is an equivalent of textread. At most, I need to be able to speficy the format of each  line in the file, i.e. the number of fields and their types. I also need to be able to skip a specified number of "header" lines at the beginning of a file.
0
Comment
Question by:ilyaz
2 Comments
 
LVL 7

Expert Comment

by:whatsit2002
ID: 17084373
I don't think you'll find anything built into the .NET framework, but here is an example of what I have done in the past to accomplish something similar:

try
{
      sr = File.OpenText(fileLocation + @"\" + fileName);
      while (sr.Peek() >= 0)
      {
            string[] row = sr.ReadLine().Split('\t');
            ProcessRow(fileName, row);
      }
      sr.Close();
}
catch {}


Where ProcessRow() is a method that uses the filename to figure out what type of record is being passed in (i.e. knows what field matches what index in the string array passed).

For other deliminters, simply pass in the correct character to the Split function.

Hope this helps.

Jason
0
 
LVL 2

Accepted Solution

by:
M3hcSS earned 125 total points
ID: 17084961
You can use the regular expression parser (regex). It works wonderfully for parsing out text files with tabs, commas, etc...

using System.Text.RegularExpressions;

http://www.csharphelp.com/archives/archive21.html

and a quick tutorial on using regex...

http://www.codeproject.com/dotnet/RegexTutorial.asp
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question