Fetch csv kind of data from text file [duplicate] - c#

This question already has answers here:
Parsing CSV files in C#, with header
(19 answers)
Closed 1 year ago.
I am having string which gives data more like to csv format .
&stamp;field1;field2;field3;field4;&event
10:44:00.6100;0.000;0.000;0.000;0.000; 10:44:00.7100;23.2;0.230;411.2;0.000; 10:44:00.8100;0.000;0.000;1.022;0.000; 10:44:00.9100;8.000;0.000;232.3;0.000;
10:44:01.2100;0.000;0.000;0.000;0.000; 10:44:01.3100;23.2;0.230;411.2;0.000; 10:44:01.5100;0.000;0.000;1.022;0.000; 10:44:01.7100;8.000;0.000;232.3;0.000;
I want to deserialize this data.

this will give you a list of strings "split" at every ; char. you will want to trim and parse the values after. hope this helps
var stringOfData = "0:44:00.6100;0.000;0.000;0.000;0.000; 10:44:00.7100;23.2;0.230;411.2;0.000; 10:44:00.8100;0.000;0.000;1.022;0.000; 10:44:00.9100;8.000;0.000;232.3;0.000;";
List<string> parsed = new List<string>();
parsed.AddRange(stringOfData.Split(';'));

string line = String.Empty;
string[] parts = null;
using (StreamReader sr = new StreamReader(new FileStream(#"C:\yourfile.csv",
FileMode.Open)))
{
while ((line = sr.ReadLine()) != null)
{
parts = line.Split(new [] { ';' });
//Do whatever you want to do with the array of values here
}
}
As for the deserialization part of the question; you would need to specify the kind of format you would want. If you just want a collection of numbers you want to loop through, you could just add every value to a generic List.
If you want a specific format, you could create a class with fields for each of those values and populate a generic list of that class using those values.

Related

How to make String.Split() work on the new line? [duplicate]

This question already has answers here:
split a string on newlines in .NET
(17 answers)
Closed 3 months ago.
string candidates;
string[] candidatesSplit = { };
string line;
int countLines = 0;
StreamReader sr = new StreamReader("..\\..\\..\\candidates.txt"); // Read candidates from file
candidates = sr.ReadToEnd();
sr.Close();
candidatesSplit = candidates.Split(','); // Split the file with ','
Console.WriteLine(candidatesSplit[30]);
Using this code, I wanted to split every ',' and get specific words out from my text file.
My candidates file looks like this:
100,Esra Tarak,90,D1,D4,D2,A,B,D,C, ,C,A,D,B,C,D,B,A, ,B,A,C,D,C,D,A,D,B,C,D
101,Cem Ak,84,D1,D5, ,A,C,D,C,C,C,A,C,B,C,D,B,A,C,B,A,C,D,C,C,A,D,B,C,D
Code works perfectly for the first line in candidates.txt, however when it comes to the second line on the text file, the output comes out like this:
D
101
I need it to show only like this
101
I cannot put a ',' at the end of my lines. Is there any way to fix this?
Just Split(Environment.NewLine) on the entire input first and then Split(',') again on each line.
using var sr = new StreamReader("..\\..\\..\\candidates.txt");
var candidates = sr.ReadToEnd();
foreach (var line in candidates.Split(Environment.NewLine))
{
var candidatesSplit = line.Split(',');
Console.WriteLine(candidatesSplit[30]);
}

Split multi JSON value into multi rows C#

I want to split a comma separated value, coming from JSON, to rows.
This
ColA:X
ColB:["1885331","2750160","151243","151241","2750159"]
To
ColA: X X
ColB:1885331 2750160 etc.
I tried to split it through Json Deserializer, but as much as I can understand the specific string isn't a list or an array. Can I split with c# ?
Is this what you want?
row.Split(',');
This should work for you. Convert your input to a string and work through it like this.
using (var sr = File.OpenText(fileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
var fields = line.Split(',');
var test = fields[0].Trim();
}
}
Then you can create any type of object you want after.

Regex split for comma and double quotes CSV format [duplicate]

This question already has answers here:
How to split csv whose columns may contain comma
(9 answers)
Closed 7 years ago.
I am not really good in Regex.
The string:
"FF","asdadasd60","Report,License","502","5A1301","I-Web Report,License","50A1","PR02","02","5A11","REL","","","","A1170600","500008","FA10","5000001","","","","","000000000.000","","000000000.000","","000000000.000","","000000000.000","","00000000","00000000","",""
I have done this but remove the double quotes before. But the result for string Report,License and I-Web Report,License are splitted. This is wrong.
I want to split it into array by comma between double quotes not inside them.
Use a real csv parser instead of using string methods or regex. You could use the TextFieldParser which is the only one available in the framework directly:
var allLineFields = new List<string[]>();
using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(new StringReader(str)))
{
parser.Delimiters = new string[] { "," };
parser.HasFieldsEnclosedInQuotes = true; // <--- !!!
string[] lineFields;
while ((lineFields = parser.ReadFields()) != null)
{
allLineFields.Add(lineFields);
}
}
You need to add a reference to the Microsoft.VisualBasic dll to your project.
There are other available: Parsing CSV files in C#, with header

CSV file contents to two dimensional array [duplicate]

This question already has answers here:
Parsing CSV files in C#, with header
(19 answers)
Closed 8 years ago.
This question has been asked several times with different inputs so I thought of reposting it with my requirement.
I have a CSV file which contents string fields in the way given below.
idnum,name1, name2,groupid
idnum,name1, name2,groupid
idnum,name1, name2,groupid
example
s001,sahil,payap,gid0
s002,Amir,Khan,gid02
d003,hrithik,roshan,gid03
I have two dimensional string array. I want to read row by row to my two dimensional array.
When it read it should be like this
arr[0][0]=s001
arr[0][1]=name1
arr[0][2]=name2
arr[0][3]=gid01
arr[1][0]=s002
arr[1][1]=Amir
arr[1][2]=Khan
arr[1][3]=gid04
there are 40 records in a file and it should read till the end of the file.
I need to implement this in C#
Any code sample or any explanation would be great help.
I have no knowledge in csv file handling so please don't ask what did you try, at least if you could give me a code sample for reading just one string for a variable it would be a great help.
And please don't ask to go for another solution.
Thanks.
The simplest way to read a csv file in the way you suggest is probably:
var rows = File.ReadAllLines("myfile.csv").Select(l => l.Split(',').ToArray()).ToArray();
Then:
Console.WriteLine(rows[0][0]); // Will output s001
Console.WriteLine(rows[0][1]); // Will output sahil
Console.WriteLine(rows[0][2]); // Will output payap
Console.WriteLine(rows[0][3]); // Will output gid0
Console.WriteLine(rows[1][0]); // Will output s002
Console.WriteLine(rows[2][0]); // Will output d003
The file would have to be read in line-wise. Each line would have to be separated using String.Split. Then the resulting strings would have to be trimmed using Trim, and finally would have to be written into the respective columns of the current row. However I totally second the comments above; more convenient would be to use some class or struct called Person and then to parse into a List<Person>.
The reading could be done as follows:
String line = String.Empty;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\file.txt");
while((line = file.ReadLine()) != null)
{
String[] parts_of_line = line.Split(',')
for ( int i = 0; i < parts_of_line.Length; i++ )
parts_of_line[i] = parts_of_line[i].Trim();
// do with the parts of the line whatever you like
}
You can do that using the CsvHelper library:
const string Csv = #"s001,sahil,payap,gid0
s002,Amir,Khan,gid02
d003,hrithik,roshan,gid03";
var rows = new List<string[]>();
string[] row;
using (var stringReader = new StringReader(Csv))
using (var parser = new CsvParser(stringReader))
while ((row = parser.Read()) != null)
{
rows.Add(row);
}
Console.WriteLine(rows[0][0]); // Will output s001
Console.WriteLine(rows[0][1]); // Will output sahil
Console.WriteLine(rows[0][2]); // Will output payap
Console.WriteLine(rows[0][3]); // Will output gid0
Console.WriteLine(rows[1][0]); // Will output s002
Console.WriteLine(rows[2][0]); // Will output d003
For a working example, check out this .NET fiddle: http://dotnetfiddle.net/PLPXo8
If you want to read directly from file, you can do this:
var rows = new List<string[]>();
string[] row;
using (var parser = new CsvParser(File.OpenText(#"c:\test.csv")))
while ((row = parser.Read()) != null)
{
rows.Add(row);
}

Convert a tab delimited file into CSV file in c# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to covert tab separated file to CSV file
i have a tab delimited text file which i have to convert into CSV file all this must be done through C# code. My txt file is very large about(1.5 GB), hence i want to convert it in a quick time. please help me.
If your input tab delimited text file does not have any commas are part of the data, then it is a very straightforward find and replace similar to the other answers here:
var lines = File.ReadAllLines(path);
var csv= lines.Select(row => string.Join(",", row.Split('\t')));
File.WriteAllLines(path, csv);
But if your data has commas, doing this is going to break your columns as you now have extra commas that are not supposed to be delimiters, but will be interpreted as such. How to handle it depends greatly on what you application you will be using to read the CSV.
A Microsoft Excel compatible CSV is going to have double quotes around fields with commas to make sure they are interpreted as data and not a delimiter. This also means that fields that contain double quotes as data will need special treatment.
I would recommend a similar approach with an extension method.
var input = File.ReadAllLines(path);
var lines = input.Select(row => row.Split('\t'));
lines = lines.Select(row => row.Select(field => field.EscapeCsvField(',', '"')).ToArray());
var csv = lines.Select(row => string.Join(",", row));
File.WriteAllLines(path, csv.ToArray());
And here's the EscapeCsvField extension method:
static class Extension
{
public static String EscapeCsvField(this String source, Char delimiter, Char escapeChar)
{
if (source.Contains(delimiter) || source.Contains(escapeChar))
return String.Format("{0}{1}{0}", escapeChar, source);
return source;
}
}
Also, if the file is large, it might be best to not read the entire file into memory. In that case, I would suggest writing the CSV output to a different file and then you could use StreamReader and StreamWriter to only work with it 1 line at a time.
var tabPath = path;
var csvPath = Path.Combine(
Path.GetDirectoryName(path),
String.Format("{0}.{1}", Path.GetFileNameWithoutExtension(path), "csv"));
using (var sr = new StreamReader(tabPath))
using (var sw = new StreamWriter(csvPath, false))
{
while (!sr.EndOfStream)
{
var line = sr.ReadLine().Split('\t').Select(field => field.EscapeCsvField(',', '"')).ToArray();
var csv = String.Join(",", line);
sw.WriteLine(csv);
}
}
File.Delete(tabPath);
var csv = File.ReadAllLines("Path").Select(line => line.Replace("\t", ","));
You could simply call
public void ConvertToCSV(string strPath, string strOutput)
{
File.WriteAllLines(strOutput, File.ReadAllLines("Path").Select(line => line.Replace("\t", ",")));
}
There is a lot of content already on SO for handling .CSV files, please search first or trying something.
If the format of your file is strict, you could use string.Split and string.Join:
var lines = File.ReadAllLines(path);
var newLines = lines.Select(l => string.Join(",", l.Split('\t')));
File.WriteAllLines(path, newLines);

Categories

Resources