Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Very small problem but its causing me some grief, I'm trying to create a CSV/TSV reader using C# which can accept both "," and "\t" as splitters.
This line works fine but when the streamreader converts the text to a string it converts \t into \\t
C#
using (StreamReader sr = File.OpenText(filepath))
{
   while ((line = sr.ReadLine()) != null) 

etc


Before it goes into the streamreader : test1 , test2 \t test3
After: test1 , test2 \\t test3

The splitters I use are below, if i have \t in the string it works fine but if its converted to \\t it doesnt work.
C#
char[] delimiterChars = { ',',  '\t'};
string[] text = line.Split(delimiterChars);


how do i either allow my program to use \\t as a char literal as well as the other delimters or stop the streamreader converting the text from \t to \\t

I was using this example for multiple delimiters but the split requires a char or char array so \\t doesnt compute since its a string http://msdn.microsoft.com/en-us/library/ms228388.aspx[^]
Posted
Comments
Freak30 4-Sep-13 9:04am    
When you write "Before it goes into the streamreader", do you mean you literally wrote \t into the file, e.g. using notepad? This would explain thebehavior.
[no name] 4-Sep-13 11:28am    
I would be willing to bet that StreamReader is not converting anything to anything else. How, exactly, are you determining that StreamReader is converting \t to \\t?
Phoenix234 4-Sep-13 16:46pm    
the csv file looks like this
1 , 2 \t 3
it goes in like that and comes out like
1 , 2 \\t 3

I used breakpoints on what was in the file and what came out after the streamreader, it adds the extra \ after it goes through.
[no name] 4-Sep-13 18:09pm    
If you are looking at it in the debugger, the visualizer is doing that not the StreamReader. That is what it is supposed to do and is perfectly normal. Nothing is being "converted" to anything. Your tab character is still just a tab character.

Yes, simple. Just use this string.split overload instead:

String.Split(String[], StringSplitOptions)

[^]
 
Share this answer
 
Comments
Phoenix234 4-Sep-13 16:58pm    
this worked perfectly! thanks for the link :)
I guess this issue is due reading as a string. I might be wrong but options I would look at is read as array of byte. Second options is read as a string same as you are doing replace \\t with \t and then split.
 
Share this answer
 

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