Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi..i want to know how can i parse a text file in Csharp.Net .I am giving an example of my textfile.
How can I extract the contents in this table (in text file ) in a datatable ?
This is the format of my textfile:
	ABC Firm Pvt Limited

	Product Catalog

Product ID	Product Name	Quantity Available
--------------------------------------------------
--------------------------------------------------
	1       PQR 			50
	2	XYZ			150
	3	EEF			15
Posted
Updated 17-Apr-12 1:38am
v2
Comments
[no name] 17-Apr-12 7:55am    
All you should really need is File.ReadAllText and String.Split.

Well, your main problem is that the textfile is in a dreadful format. If your columns are always the same (and the header) I'd just discard the first seven lines, then split the following lines on tabs.

How can the computer tell if 'Product Name' is one column with values, or two columns 'Product' and 'Name' with nothing in the second column?

Not much help, but if possible try getting the file in a better format.
 
Share this answer
 
v2
Comments
sagar wasule 17-Apr-12 7:51am    
I don't have any other format of the file , while my actual file contains some 10 columns which makes things quite cumbersome when I parse the file character by character , hence was searching for any other option. The file which I have do have the header text same.
Rob Philpott 17-Apr-12 7:54am    
Don't do it character by character. Read the file a line at a time using something like StreamReader.ReadLine(). Discard first 7 lines. If you know that for every column and every row there will be a value, do a string.Split on the line using tab as the delimiter using the option to remove empty records. You then end up with a string array for each line you can add to a datatable.

If some 'cells' might not have data, you'll need to define tab stops to identify where data is in each row.
Hi,

To parse text in C#, you need to use following string function:

IndexOf()
LastIndexOf()
SubString()
Replace()
StartsWith()
EndsWith()

etc.
 
Share this answer
 
Comments
sagar wasule 17-Apr-12 7:46am    
So are you saying that I have to parse character by character ????
Deepak_Sharma_ 17-Apr-12 8:03am    
Yes because you have to apply your own logic for what you want to extract from the text. Like "Product ID" will start where this heading "------" ends.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900