read .csv file into 1D array c# - c#

I would like to convert this code from java to C#
I need to write line by line from csv and store it in an array?
String csvFile = "data.csv";
String line = "";
String cvsSplitBy = ",";
try (BufferedReader br = new BufferedReader(new FileReader(csvFile)))
{
while ((line = br.readLine()) != null)
{
// use comma as separator
String[] data = line.split(cvsSplitBy);
System.out.println(Integer.parseInt(data[0]) + " "+data[1] + " "+data[2] );
}
}
catch (IOException e)
{
e.printStackTrace();
}
Any suggestions?

If you are trying to parse each record/row into array, this might help.
using (StreamReader sr = new StreamReader("maybyourfilepat\data.csv"))
{
string line = sr.ReadLine();
//incase if you want to ignore the header
while (line != null)
{
string[] strCols = line.Split(',');
line = sr.ReadLine();
}
}

Related

Split an existing indexed array

Im Attempting to read a .txt file that is seperated by commas and two lines, currently i have it setup so that it reads the txt file but having trouble with using the.split method with the taxArray, i need to use the .split so i can calulate the differnt values.
string[] taxArray = new string[2];
int count = 0;
try
{
if(File.Exists(filePath))
{
//read the lines from text file add each line to its own array index.
foreach (string line in File.ReadLines(filePath, Encoding.UTF8))
{
taxArray[count] = line;
txtDisplay.Text += taxArray[count] + "\r\n";
count++;
}
}
else
{
MessageBox.Show("This file cannot be found");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
This currently outputs exactly as i need.
Here was my solution, I was calling to the array before the foreach loop did its job reading the txt file, thanks for the assistance Toby <3
string[] taxArray = new string[2];
int count = 0;
// string incomeBracket = taxArray[0];
//string[] incomeBracketArray = incomeBracket.Split(',');
try
{
if(File.Exists(filePath))
{
//read the lines from text file add each line to its own array index.
foreach (string line in File.ReadLines(filePath, Encoding.UTF8))
{
taxArray[count] = line;
txtDisplay.Text += taxArray[count] + "\r\n";
count++;
}
string[] incomeBracket = taxArray[1].Split(',');
txtDisplay.Text = incomeBracket[0];
else
{
MessageBox.Show("This file cannot be found");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

c# function inside while won't cycle

hi everybody i have this code
StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt");
string line = reader.ReadLine();
string app = "";
int i = 0;
while (line != null)
{
i++;
line = reader.ReadLine();
if (line != null)
{
int lunghezza = line.Length;
}
Console.WriteLine(i);
System.Threading.Thread.Sleep(800);
string ris= traduttore.traduci(targetLanguage, line);
// Console.WriteLine(line);
// Console.WriteLine(ris);
// Console.Read();
// app = app + ris;
// System.Threading.Thread.Sleep(50);
File.AppendAllText(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt", ris + Environment.NewLine);
}
the fact is that i have a txt file which i want to translate with this function traduci(targetLanguage,line), the function is ok, i want to translate each line into another file, while is looping the function is blocking at the first loop, if i insert consonle.read() when i press enter the function works...ho can i do? thank you all!
Your code is pretty messy. I would suggest the following method to loop over the StreamReader lines:
using (StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt"))
{
string line;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
// ... process the line
}
}
If ReadLine returns a null, your code will break. better structure:
StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt");
string line;
string app = "";
int i = 0;
while ((line = reader.ReadLine()) != null)
{
i++;
int lunghezza = line.Length;
Console.WriteLine(i);
System.Threading.Thread.Sleep(800);
string ris= traduttore.traduci(targetLanguage, line);
// Console.WriteLine(line);
// Console.WriteLine(ris);
// Console.Read();
// app = app + ris;
// System.Threading.Thread.Sleep(50);
File.AppendAllText(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt", ris + Environment.NewLine);
}
The code as it stands will skip over the first line, as you use ReadLine() twice prior to fist use.
You can restructure the code as
using (StreamReader reader = new StreamReader(#"C:\Users\lorenzov\Desktop\gi_pulito_neg.txt"))
using (StreamWriter writer = new StreamWriter(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt"))
{
string line = reader.ReadLine();
while(line != null)
{
System.Threading.Thread.Sleep(800);
string ris = traduttore.traduci(targetLanguage, line);
writer.WriteLine(ris);
line = reader.ReadLine();
}
}

Parsing CSV data

I am trying to parse a CSV file with data with no luck, i have tried a bunch of tools online and none has been able to parse the CSV file correctly. I am baffled by the fact that i am in here asking for help as one would think parsing CSV data would be something super easy.
The format of the CSV data is like this:
",95,54070,3635,""Test Reservation"",0,102,0.00,0.00,2014-12-31,""Name of customer"",""$12.34 + $10, special price"",""extra information"",,CustomerName,,,,,1234567890,youremail#domain.com,CustomerName,2014-12-31,23:59:59,16,0,60,2,120,0,NULL,NULL,NULL,"
Current code:
private void btnOpenFileDialog_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
using (StreamReader reader = new StreamReader(openFileDialog1.FileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
ParseCsvLine(line);
}
}
}
}
private void ParseCsvLine(string line)
{
if (line != string.Empty)
{
string[] result;
using (var csvParser = new TextFieldParser(new StringReader(line)))
{
csvParser.Delimiters = new string[] { "," };
result = csvParser.ReadFields();
}
foreach (var item in result)
{
Console.WriteLine(item + Environment.NewLine);
}
}
}
The result variable only has one item and its:
,95,54070,3635,"Test Reservation",0,102,0.00,0.00,2014-12-31,"Name of customer","$12.34 + $10, special price","extra information",,CustomerName,,,,,1234567890,youremail#domain.com,CustomerName,2014-12-31,23:59:59,16,0,60,2,120,0,NULL,NULL,NULL,
// Add Microsoft.VisualBasic.dll to References.
using Microsoft.VisualBasic.FileIO;
// input is your original line from csv.
// Remove starting and ending quotes.
input = input.Remove(0, 1);
input = input.Remove(input.Length - 1);
// Replace double quotes with single quotes.
input = input.Replace("\"\"", "\"");
string[] result;
using (var csvParser = new TextFieldParser(new StringReader(input)))
{
csvParser.Delimiters = new string[] { "," };
result = csvParser.ReadFields();
}
You can check out a previous post that deals with those pesky commas in csv files. I'm linking it here.
Also Mihai, your solution works well for just the one line but will fail once there are many lines to parse.

Extract data from text file

I need to extract some data from a text file and insert to columns in excel sheet. I know how to do this if the rows and the length of the string is known.
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader("test.txt")
{
string line;
while ((line = sr.ReadLine()) != null)
{
listSNR.Items.Add(line.Substring (78,4));
}
}
}
But the particular text file is complex and the starting index or the length cannot be provided. But the starting word (PCPU01) of the row is known.
Eg: PCPU01,T2716,0.00,0.01,0.00,0.00
output:
T2716 0 0.01 0 0
In that case can somebody please let me know how to extract the texts?
using(System.IO.StreamReader sr = new System.IO.StreamReader("test.txt"))
{
string line;
while((line = sr.ReadLine()) != null)
{
string[] split = line.Split(',');
//...
}
}
split[0] will return "PCPU01", split[1] "T2716" and so on.
You can split one string into an array of strings, separated by a given character. This way, you could split the source string by a comma and use the resulting strings to build your output. Example:
string source = "PCPU01,T2716,0.00,0.01,0.00,0.00";
string[] parts = source.Split(',');
StringBuilder result = new StringBuilder();
result.Append(parts[1]); // The second element in the array, i.e. T2716
result.Append(" ");
result.Append(parts[2]); // 0.00
... // And so on...
return result.ToString() // return a string, not a StringBuilder
I hope this helps a little bit. You might have to tweak it to your needs. But this is a higher level code that gives you general idea of extracting data off a notepad.
DialogResult result = openFileDialog.ShowDialog();
Collection<Info> _infoCollection = new Collection<Info>();
Collection<string> listOfSubDomains = new Collection<string>();
string[] row;
string line;
// READ THE FILE AND STORE IT IN INFO OBJECT AND STORE TAHT INFO OBJECT IN COLLECTION
try
{
using (StreamReader reader = new StreamReader(openFileDialog.FileName))
{
while((line = reader.ReadLine()) != null)
{
Info _info = new Info();
row = line.Split(' ');
_info.FirstName = row[0];
_info.LastName = row[1];
_info.Email = row[2];
_info.Id = Convert.ToInt32(row[3]);
_infoCollection.Add(_info);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
thanks for the answers. What i wanted is to identify the particular line in the text file and split the line into columns. So i was able to do this by calling a GetLine method:
string line15=GetLine(#"test.txt",15);
public string GetLine(string fileName, int line)
{
using (System.IO.StreamReader ssr = new System.IO.StreamReader("test.txt"))
//using (var ssr = new StreamReader("test.txt"))
{
for (int i = 1; i < line; i++)
ssr.ReadLine();
return ssr.ReadLine();
}
}
Then i splitted this line by using the delimiter (,)
This was my approach in C#. It takes a string input (which you can get out of a text file) and an int with which line you want to get. It then separates the string at a given seperator char to a list which in turn is then read out. If the given line number is lower than the count of the created list, the entry is given back.
public string GetLine(string multiline,int line)
{
List<string> lines = new List<string>();
lines = multiline.Split('\n').ToList<string>();
return lines.Count >= line ? lines[line] : "";
}

Reading input value from textbox, fetching the data from Textfile and displaying the result

I need help in searching the text file. I have manage to store the input values to Textfile with ":" separator.
And my result text box is like
friend1:126457890
friend2:123487012
Friend3:798461598
and now I want to search the text file and display result in labels/textbox(read only)
Here is my code to search
private void btn_search_search_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txt_search.Text))
{
lbl_search_error.Text = "Please Enter name to search";
}
else
{
StreamReader sr = new StreamReader(#"path.txt");
string line;
string searchkey = txt_search.Text;
sr.ReadToEnd();
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(searchkey))
break;
}
sr.Close();
string[] data = line.Split(':');
txt_result_name.Text = data[0];
txt_result_phno.Text = data[1];
}
}
catch (Exception ex)
{
lbl_search_error.Text = ex.Message;
}
}
but I get
Object reference not set to an instance of an object
I tried to keep break point and chk, error is in this line
string[] data = line.Split(':');
Please help resolving
Thank you for your time
Delete the line sr.ReadToEnd();
Let me give you a different approach using regular expression:
private void btn_search_search_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("Some file");
string line = sr.ReadLine();
string name="";
string number="";
while (line != null)
{
var m = Regex.Match(line, #"([\w]+):([\d]+)<br>");
if (m.Success)
{
name = m.Groups[1].Value;
number = m.Groups[2].Value; // use this name and number variables as per your need
line = sr.ReadLine();
}
else
{
line = sr.ReadLine();
}
}
}
This is a way to go about the problem. Ask any questions if you have
You are getting this error because the value of line is null in: string[] data = line.Split(':');
Take a string variable called temp and assign the value of line to temp in the while loop. Later use this variable instead of line.
Do like this:
private void btn_search_search_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(txt_search.Text))
{
lbl_search_error.Text = "Please Enter name to search";
}
else
{
StreamReader sr = new StreamReader(#"path.txt");
string line;
string searchkey = txt_search.Text;
sr.ReadToEnd();
string temp;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains(searchkey))
{
temp = line;
break;
}
}
sr.Close();
string[] data = temp.Split(':');
txt_result_name.Text = data[0];
txt_result_phno.Text = data[1];
}
}
catch (Exception ex)
{
lbl_search_error.Text = ex.Message;
}
}

Categories

Resources