Reading file with C# - c#

I want to read php text file using c#. The file looks like:
2.20:2.20:2.20:2.20:2.20:
2012-07-12:2012-07-11:2012-07-10:2012-07-09:2012-07-08:
I would like to get all lines to listboxes. In real situation there is six lines, but first I should have read these two lines. My code:
void web_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
int i;
string price_line = "";
string date_line = "";
List<decimal> prices = new List<decimal>();
List<string> dates = new List<string>();
using (var reader = new StreamReader(e.Result))
{
price_line = reader.ReadLine();
date_line = reader.ReadLine();
string[] bit_1 = price_line.Split(':');
string[] bit_2 = date_line.Split(':');
for (i = 0; i < 2; i++)
{
prices.Add(decimal.Parse(bit_1[i]));
dates.Add(bit_2[i]);
}
listBox1.ItemsSource = prices;
listBox2.ItemsSource = dates;
}
}
catch
{
MessageBox.Show("Can't read!");
}
}
Now I get "NullException". How to fix this?

EDIT:
What's about:
using (StreamReader reader = new StreamReader(e.Result))
{
List<string> lines = new List<string>();
while (!reader.EndOfStream)
lines.Add(reader.ReadLine());
string prices = lines.First().Split(':');
List<decimal> listPrices = new List<decimal>();
List<string> listDates = lines.Last().Split(':').ToList();
foreach(string s in prices)
listPrices.Add(double.Parse(s));
listBox1.ItemsSource = listPrices;
listBox2.ItemsSource = listDates;
}
You should check if e.Result, listBox1 and listBox2 aren't null.

Related

C# string array.length error when calling from a CSV file

I'm fairly new to C# and im writing a rental vehicle management system. I'm trying to retrieve all lines from a CSV file that is set up like this:
[Registration][Grade][Make][Model][Year][NumSeats][Transmission][Fuel][GPS][SunRoof][DailyRate][Colour]
[123ABC][Economy][Toyota][Camry][2005][5][Automatic][Petrol][No][No][30][White]
[234BCD][Economy][Ford][Focus][2012][5][Automatic][Petrol][Yes][No][45][Blue]
[987ZYX][Economy][Holden][Cruise][2016][5][Manual][Diesel][Yes][No][60][Red]
and then iterate it through a for loop before it's sent to another method.
In the following method beyond the one shown, it's being put into an ArrayList so that the values retrieved can be searched for by the user in the program.
I'm stuck on the for loop as it gives me an error on the vehicles1.Length; saying that vehicles1 is a use of an unassigned local variable. I don't know if initializing the array is my problem, because I've tried that and it gives me no errors but the program just breaks.
void setUpVehicles(out Fleet fleetVehicles)
{
const char DELIM = ',';
Vehicle veh = new Vehicle();
FileStream inFile = new FileStream(FILENAME3, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
string recordIn;
string[] vehicles1;
recordIn = reader.ReadLine();
while (recordIn != null)
{
string year = veh.Year.ToString();
string seats = veh.NumSeats.ToString();
string gps = veh.GPS.ToString();
string sunRoof = veh.SunRoof.ToString();
string dailyRate = veh.DailyRate.ToString();
vehicles1 = recordIn.Split(DELIM);
veh.Registration = vehicles1[0];
veh.Grade = vehicles1[1];
veh.Make = vehicles1[2];
veh.Model = vehicles1[3];
year = vehicles1[4];
seats = vehicles1[5];
veh.Transmission = vehicles1[6];
veh.Fuel = vehicles1[7];
gps = vehicles1[8];
sunRoof = vehicles1[9];
dailyRate = vehicles1[10];
veh.Colour = vehicles1[11];
}
fleetVehicles = new Fleet();
for (int i = 0; i < vehicles1.Length; i++)
{
fleetVehicles.insertVehicle(vehicles1[i]);
}
}
IEnumerable<Vehicle> setUpVehicles(string fileName)
{
using(var reader = new StreamReader(fileName))
using(var parser = new Microsoft.VisualBasic.TextFieldParser(reader))
{
parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
parser.Delimiters = new string[] {","};
string[] row;
while(!parser.EndOfData)
{
row = parser.ReadFields();
var vehicle = new Vehicle {
Registration = row[0],
Grade = row[1],
Make = row[2],
Model = row[3],
Year = row[4],
NumSeats = row[5],
Transmission = row[6],
Fuel = row[7],
GPS = row[8],
SunRoo = row[9],
DailyRate = row[10],
Colour = row[11]
};
yield return vehicle;
}
}
}
Then you would call it to make a fleet like this:
var fleetVehicles = new Fleet();
foreach(var vehicle in setUpVehicles(FILENAME3))
{
feetVehicles.insertVehicles(vehicle);
}

Using CSVHelper to read a CSV file and need to extract columns to arrays

I have this code here that works how I want, but I'm developing on .Net Standard and cannot use the Microsoft.VisualBasic.FileIO library. I would like to be able to do the same thing using CsvHelper
Is it possible with CsvHelper to, first get the header row as a string array. Second, get each row as a string array of items?
using Microsoft.VisualBasic.FileIO;
using (TextFieldParser csvParser = new TextFieldParser("FilePath"))
{
csvParser.CommentTokens = new string[] { "#" };
csvParser.SetDelimiters(new string[] { "," });
csvParser.HasFieldsEnclosedInQuotes = true;
csvParser.TrimWhiteSpace = true;
string[] fields = csvParser.ReadFields();
int arraySize = fields.Length;
int index = Array.IndexOf(fields, columnExtracted);
while (!csvParser.EndOfData)
{
fields = csvParser.ReadFields();
string column = fields[index];
Console.WriteLine(column);
}
}
I tried the following code that reads the cells but breaks the line when faced with a delimiter because of the line string Csv = string.Join("\n", result.ToArray());
Is there a way to put all the info in an array? It's already stored in a string list but I cannot retrieve the data by an index.
List<string> result = new List<string>();
string value;
using (TextReader fileReader = File.OpenText("FilePath"))
{
var csv = new CsvReader(fileReader, CultureInfo.InvariantCulture);
csv.Configuration.HasHeaderRecord = true;
while (csv.Read())
{
for (int i = 0; csv.TryGetField<string>(i, out value); i++)
{
result.Add(value);
}
if (csv.Read() == false)
break;
}
}
string Csv = string.Join("\n", result.ToArray());
EDIT
This is my new code now after the feedback. But, it seems that it's leaving out the header row when iterating through the List that stores all the records.
public List<string> HeaderColumnParser(string columnExtracted, string PathToFile)
{
List<string> result = new List<string>();
string value;
using (TextReader fileReader = File.OpenText(PathToFile))
{
var csv = new CsvReader(fileReader, CultureInfo.InvariantCulture);
csv.Read();
csv.ReadHeader();
string[] header = csv.Context.HeaderRecord;
int extractedIndex = Array.IndexOf(header, columnExtracted);
while (csv.Read())
{
string[] row = csv.Context.Record;
string column = row[extractedIndex];
result.Add(column);
}
}
return result;
This should work if you want each row as a string array.
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
using (StreamReader reader = new StreamReader(stream))
using (CsvReader csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
writer.WriteLine("Id,Name,Column3,Column4,Column5");
writer.WriteLine("1,One,Item1,Item2,Item3");
writer.WriteLine("2,Two,Item4,Item5,Item6");
writer.Flush();
stream.Position = 0;
reader.BaseStream.Position = 0;
csv.Read();
csv.ReadHeader();
string[] header = csv.Context.HeaderRecord;
var columnExtracted = "Column3";
int extractedIndex = Array.IndexOf(header, columnExtracted);
while (csv.Read())
{
string[] row = csv.Context.Record;
var column = row[extractedIndex];
Console.WriteLine(column);
}
}
Console.ReadKey();

Program stops working after selected index change second time listview c#

i have a problem that i change selected index in listview it works fine when i change first time but when i change second time it says "InvalidArgument=Value of '0' is not valid for 'index'."
the code is this ;
listBox1.Items.Clear();
string a = "";
a = "";
a = listView1.SelectedItems[0].SubItems[0].Text;
StreamReader oku = new StreamReader(strPath+"\\"+"Versiyonlar"+"\\"+a);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
foreach (var item in dizi)
{
listBox1.Items.Add(item);
}
oku.Close();
strpath is way to desktop
try
{
listBox1.Items.Clear();
string a = "";
a = "";
a = listView1.SelectedItems[0].SubItems[0].Text;
StreamReader oku = new StreamReader(strPath+"\\"+"Versiyonlar"+"\\"+a);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
foreach (var item in dizi)
{
listBox1.Items.Add(item);
}
oku.Close();
}
catch
{
}
i just fixed it like this

Separate string from list C#

I have list of string and each of that strings in list look like this: sim_pin: 1234. List have 24 strings, and I wanna to get each of that strings, separate string where separator will be : ( : and space), and save to list only that part who is right from separator.
EDIT:
Here is my code
string url = #"E:\Sims.log";
public static IEnumerable<DiverGate> GetData(string url)
{
Stream stream = File.Open(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (StreamReader sr = new StreamReader(stream))
{
string str = sr.ReadToEnd();
string[] lines = Regex.Split(str, "\r\n");
List<string> lista = new List<string>();
foreach (string line in lines)
{
lista.Add(line);
}
List<string> header = lista.GetRange(0, 23);
//I stop here and im out of idea
}
}
Something like this should work:
where input is your original list of strings
List<string> output = new List<string>();
input.ForEach(x=> output.Add(x.Split(new[] {": "},StringSplitOptions.None).Last()));
var List1 = new List<string>{"sim_pin: 1234", "sim_pin: 2345", "sim_pin: 3456"};
var List2 = new List<string>();
foreach (var s in List1) {
var ns = s.Split(':')[1].TrimStart(' ');
List2.Add(ns);
}
try this code:
for ( int i =0; i< yourList.Count(); i++) {
string s = yourList[i];
int i = s.indexOf(":");
s = s.Substring (i);
yourList.Insert(i, s);
}

Adding a string to a List<string> inside of a List<List<string>>

Im trying to add a string object to a list inside of list> in a for & while loop, trying to use var i as the list object i wish to use.
here is the code of the class, any help on what im doing wrong would be very much appreciated :)
public class GenClass
{
private static int _genCount;
private static bool _filesLoadedToLists;
private static List<string> _nounSetOne = new List<string>();
private static List<string> _nounSetTwo = new List<string>();
private static List<List<string>> _toLoad = new List<List<string>>();
private string _emotionMidTrim = "";
public const string FileOne = "NounSetOne.txt";
public const string FileTwo = "NounSetTwo.txt";
public GenClass()
{
while (_filesLoadedToLists == false)
{
TextToList(FileOne,FileTwo);
_filesLoadedToLists = true;
}
_genCount++;
}
the problem is withing this part of the class
public void TextToList(string fileOne, string fileTwo)
{
List<string> filesToRead = new List<string>();
filesToRead.Add(fileOne); // Add the text files to read to a list
filesToRead.Add(fileTwo); // Add the text files to read to a list
_toLoad.Add(_nounSetOne); // Add a list of words to this list
_toLoad.Add(_nounSetTwo); // Add a list of words to this list
for (int i = 0; i <= filesToRead.Count; i++)
{
using (var reader = new StreamReader(filesToRead[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_toLoad[i.Add(line)]; // the error is here
}
}
}
Try using File.ReadAllLines(). Replace the for loop with:
foreach(var file in filesToRead) {
_toLoad.Add(File.ReadAllLines(file).ToList());
}
You are correct, with the error, you need to understand that the
List<List<string>> will take a List<string> and NOT A String.
Try something like this;
List<string> listOfString = new List<string>;
for (int i = 0; i <= filesToRead.Count; i++)
{
using (var reader = new StreamReader(filesToRead[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
listOfString.add(line);
}
}
}
Then,
_toLoad.add(listOfStrings);
You can cut this down considerably using LINQ:
List<string> filesToRead = new List<string> {"NounSetOne.txt", "NounSetTwo.txt"};
List<List<string>> _toLoad = new List<List<string>>();
_toLoad.AddRange(filesToRead.Select(f => File.ReadAllLines (f).ToList() ));
Note that there's no extraneous variables for the filename (why have FileOne/FileTwo if their only purpose is to get added to a list?) and that we're letting the AddRange take care of creating the List<string>s for us automatically.
for (int i = 0; i <= filesToRead.Count; i++)
{
using (var reader = new StreamReader(filesToRead[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_toLoad[i].Add(line);
}
}
}

Categories

Resources