Read file using FileDialog and save to the List<> - c#

I am trying to read text file and store the information into the List<>.
So far, I managed to read strings off the file and split it, but having trouble storing the information onto the List<>. Perhaps I am trying to do too many things under one function.
using System.IO;
private void openFileDialog_Click(object sender, EventArgs e)
{
if (myOpenFileDialog.ShowDialog() == DialogResult.OK) ;
using (FileStream fStream = File.OpenRead(myOpenFileDialog.FileName))
{
StreamReader reader;
reader = new StreamReader(fStream);
string line;
while ((line = reader.ReadLine()) != null)
{
string[] playerInfo = line.Split(';');
int ID = int.Parse(playerInfo[0]);
string firstName = playerInfo[1];
string lastName = playerInfo[2];
DateTime dob = DateTime.Parse(playerInfo[3]);
List<Player> players = new List<Player>
players.add(new Player(id, firstName, lastName, dob);
}
}
}
When I check with MessageBox.Show, it comes out with 0 for the amount of lines I have in the file...
Perhaps my list.add code is in wrong place.
Thank you for your help and your time

You're creating a new List every time you're iterating over a new line, that's probably why you're not getting the correct amount of lines.
I also saw you have a few sintax errors in your code, I'll asume that you didn't copy/paste the code directly from the source and that's the reason of those errors (The Add method is in uppercase, and you missed the parentheses when initializing the List)
The working code would be like this:
List<Player> players = new List<Player>();
while ((line = reader.ReadLine()) != null) {
string[] playerInfo = line.Split(';');
int ID = int.Parse(playerInfo[0]);
string firstName = playerInfo[1];
string lastName = playerInfo[2];
DateTime dob = DateTime.Parse(playerInfo[3]);
players.Add(new Player(id, firstName, lastName, dob);
}
If you want to have access to the list more globally you could do it this way:
Let's assume your class name is Sample:
public class Sample {
// Declare the list as a private field
private List<Player> players;
// Constructor - Creates the List instance
public Sample() {
players = new List<Player>();
}
private void openFileDialog_Click(object sender, EventArgs e) {
players.Clear(); //Clears the list
if (myOpenFileDialog.ShowDialog() == DialogResult.OK) ;
using (FileStream fStream = File.OpenRead(myOpenFileDialog.FileName)) {
StreamReader reader;
reader = new StreamReader(fStream);
string line;
while ((line = reader.ReadLine()) != null) {
string[] playerInfo = line.Split(';');
int ID = int.Parse(playerInfo[0]);
string firstName = playerInfo[1];
string lastName = playerInfo[2];
DateTime dob = DateTime.Parse(playerInfo[3]);
players.Add(new Player(id, firstName, lastName, dob);
}
}
}
}
Declaring the list this way you'll be able to get the values of the list from other methods inside the same class.

Related

Console App...Objects of a Class

I have created 2 classes. One class has instance variables, default constructor, constructor with parameters, properties and one function/method. the second class, contains my main method and is required to read data from a txt. file and then save the data to the 3 different objects.
I created 3 objects that look like this
NewEmployee employee1 = new NewEmployee();
this is what my code looks like to read the text file
using (StreamReader stream = new StreamReader(#"C:\Users/path))
{
while((line = stream.ReadLine()) != null)
{
Console.WriteLine(line);
}
How do I save the data from the text file to each object?
This is what the text file looks like:
First Name
Last Name
IdNUm
Start Year
Initial Salary
repeats 2x
I think this is what the OP wants:
List<Employee> employees = new List<Employee>();
using (StreamReader sr = new StreamReader("filepath"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] split = line.Split(" ".ToCharArray());
employees.Add(new Employee
{
FirstName = split[0],
LastName = split[1],
EmployeedID = Int32.Parse(split[2]),
StartYear = Int32.Parse(split[3]),
InitialSalary = Decimal.Parse(split[4])
});
}
}
This assumes the lines are delimited by space and that the values will cast into the proper types. You can add the error handling but this will get you started.

Split array and add to new array in while loop

I have a flat file that I am reading in C# and then attempting to parse. I mean to store the account number in the flat file in an array.
AccountNumber | AccountName | DateCreated
1 | Bob | 1/1/2011
2 | Donna | 3/2/2013
3 | Jake | 2/21/2010
5 | Sally | 4/2/2014
So far this is what my splitting looks like:
//List<string[]> myArrayList = new List<string[]>();
using (StreamReader read = new StreamReader(#"C:\text\Accounts.txt"))
{
string line;
while ((line = read.ReadLine()) != null)
{
string[] parts = line.Split('|');
Console.WriteLine(parts[0]);
//myArrayList.Add(parts[0]);
}
}
How do I store everything that's printed in parts[0] in it's own array outside of the while loop? I've tried doing a list add but I keep getting errors for invalid arguments. I commented out the bits that don't work.
the following code reads the contents of the file, splits the lines, stores it in a list and finally displays the first column in a RichTextBox
private void button1_Click(object sender, EventArgs e)
{
List<string[]> myArrayList = new List<string[]>();
StreamReader read = new StreamReader(#"C:\test\Accounts.txt");
string line;
while ((line = read.ReadLine()) != null)
{
string[] parts = line.Split('|');
//Console.WriteLine(parts[0]);
myArrayList.Add(parts);
}
foreach (var account in myArrayList)
{
richTextBox1.Text = richTextBox1.Text + account[0].ToString() + Environment.NewLine;
}
}
I like MethodMan's suggestion:
// Class structure
public class Account
{
public int AccountNumber;
public string AccountName;
public DateTime DateCreated;
public Account(string[] info)
{
// This is all dependent that info passed in, is already valid data.
// Otherwise you need to validate it before assigning it
AccountNumber = Convert.ToInt32(info[0]);
AccountName = info[1];
DateCrated = DateTime.Parse(info[2]);
}
}
Your code using the class structure:
List<Account> myAccounts = new List<Account>();
using (StreamReader read = new StreamReader(#"C:\text\Accounts.txt"))
{
string line;
while ((line = read.ReadLine()) != null)
{
string[] parts = line.Split('|');
myAccounts.Add(new Account(parts));
}
}
// Do whatever you want after you have the list filled

Write into the CSV

at first I am a novice, I am learning is that only two months. (Sorry for my english, I hope u will understand.)
Problem is:
I am trying to create a small database with console application. I have student.csv where are all information about students. When I start application, all informations from this .csv will save into Lists. Like this:
List<Student> zoznam = new List<Student>();
List<string> inicZac = new List<string>();
List<string> ID = new List<string>();
List<string> Meno = new List<string>();
List<string> Priezvisko = new List<string>();
List<string> Adresa = new List<string>();
List<string> DatumNarodenia = new List<string>();
List<string> Heslo = new List<string>();
List<string> Login = new List<string>();
List<string> inicKon = new List<string>();
private int id;
StreamReader reader = new StreamReader(File.OpenRead("student.csv"));
public databazaStudentov()
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
inicZac.Add(values[0]);
ID.Add(values[1]);
Meno.Add(values[2]);
Priezvisko.Add(values[3]);
Adresa.Add(values[4]);
DatumNarodenia.Add(values[5]);
Heslo.Add(values[6]);
Login.Add(values[7]);
inicKon.Add(values[8]);
zoznam.Add(new Student(values[1], values[2], values[3], values[4], values[5], values[6], values[7]));
}
}
It works good. But now I want secure an easy write into this .csv when I create a new student in a running application.This function is creating a new student:
public void addStudent(string meno, string priezvisko, string adresa, string datum)
{
string tempID = generujID(); //random gener ID
string tempLogin = generujLogin(meno, priezvisko); //random gener Login
string tempHeslo = generujHeslo(); //random gener password
zoznam.Add(new Student(tempID, meno, priezvisko, adresa, datum, tempLogin, tempHeslo));
ID.Add(tempID);
Meno.Add(meno);
Priezvisko.Add(priezvisko);
Adresa.Add(adresa);
DatumNarodenia.Add(datum);
Login.Add(tempLogin);
Heslo.Add(tempHeslo);
// I created a new student and now I want save him into the csv
}
and here is my .csv: http://i.imgur.com/P0PnxpB.jpg?1
There are probably more ways how to fix it. I will be gratefull if someone show me How to save a new student on a new row or How to overwrite with Lists everything in my student.csv . Thanks for tips and sorry for my english.
I would create a new class to create csv file from your student.
public class CsvGen
{
private _fileName=string.Empty;
private StringBuilder csvRows;
public CsvGen(string fileName)
{
_fileName=fileName;
csvRows=new StringBuilder();
}
public void Add(Student student)
{
var row=String.Format("{0},{1},{2},{3}",student.Id,student.Name,student.City,
Environment.NewLine);
csvRows.Append(row);
}
public void SaveFile()
{
System.IO.File.WriteAllText(_fileName,csvRows.ToString());
}
}
Now from your other class, you can create a new instance of this class and call the AddStudent method everytime you add an item to the list and call SaveFile after your loop.
CsvGen csvGen=new CsvGen(#"C:\\temp\myFile.csv");
// ^ any location with proper permission for .net to write files.
public void AddStudent(int id, string name, string city)
{
Student stud=new Student();
stud.Id=id;
stud.Name=name;
stud.City=city;
csvGen.Add(stud);
}
So once you create all students, You may call the SaveFile method to save the csv file
while (!someCondition)
{
AddStudent(2,"scott","detroit");
}
csvGen.SaveFile();
A quick solution for your question.
public void addStudent(string meno, string priezvisko, string adresa, string datum)
{
//your code
//.........
// I created a new student and now I want save him into the csv
using(StreamWriter sw = new StreamWriter("student.csv", true))//true to append after the file
{
sw.WriteLine("{0};{1};{2};{3};{4};{5};{6};",
tempID, meno, priezvisko, adresa, datum, tempLogin, tempHeslo);
sw.Close();
}
}
If you want to read and write csv, then I'd recommend you try the CsvHelper library, as it would be much simpler than the way you're doing it currently.

Looping through an array to add parameters to sql query

I am reading rows out of a text file and storing them to an array. I now need to then loop through the items in every array position. I can loop through the rows in the document but I need to loop through the array values as well.
Here is my code for reading the text file and building the array :
public class people
{
public string name;
public int empid;
public string address;
}
private void read()
{
using (StreamReader sr = new StreamReader(#"E:\test.txt"))
{
while (sr.Peek() >= 0) << This loops through the rows in the text doc
{
string str;
string[] strArray;
str = sr.ReadLine();
strArray = str.Split(',');
people new_people = new people();
new_people.name = strArray[0];
new_people.empid = int.Parse(strArray[1]); // << I need to be able to loop through each of
new_people.address = strArray[2]; // these and add each on to my query string
peoples.Add(new_people);
listBox1.Items.Add(new_people.name + new_people.empid + new_people.address); //< this displays
// the array values
}
}
I need something like this :
foreach (string foo in new_people.name[0] )
{
cmd.Parameters.Add("#1", SqlDbType.VarChar).Value = foo ;
// then do this for every item in the array for that position
cmd.Parameters.Add("#2", SqlDbType.VarChar).Value = (next set of values);
cmd.Parameters.Add("#3", SqlDbType.VarChar).Value = (next set of values);
cmd.ExecuteNonQuery();
}
Creating your own constructor will help you to create instances of Person class (person is singular, people is plural):
public class Person
{
public string Name;
public int Empid;
public string Address;
public Person(string name, int empid, string address)
{
Name = name;
Empid = empid;
Address = address;
}
}
private void read()
{
using (StreamReader sr = new StreamReader(#"E:\test.txt"))
{
while (sr.Peek() >= 0)
{
string str;
string[] strArray;
str = sr.ReadLine();
strArray = str.Split(',');
Person newPerson = new Person(strArray[0], int.Parse(strArray[1]), strArray[2]);
people.Add(newPerson);
listBox1.Items.Add(newPerson.Name + newPerson.Empid + newPerson.Address);
}
}
You can then loop through all names:
int i = 0;
foreach (Person p in people)
cmd.Parameters.Add("#" + (i++), SqlDbType.VarChar).Value = p.Name;
cmd.ExecuteNonQuery();

Parsing data from a text file into an array

I have a flat text file that contains the following data;
Following are the names and ages in a text file.
26|Rachel
29|Chris
26|Nathan
The data is kept on a server (e.g http://domain.com/info.dat), I'd like to read this text file and insert it into an array (age and name). I'd like to ignore the first line (Following are....).
I've sorted the code to grab the data file using a webclient and the code to open the dat file using streamreader as follows;
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
string[] channels = Text.Split('|');
foreach (string s in channels)
{
}
}
}
The problem with the above code is when it comes to inputting it into an array with the correct columns. Could anyone give me some pointers?
Many thanks
How about an answer that uses some LINQ:
var results = from str in File.ReadAllLines(path).Skip(1)
where !String.IsNullOrEmpty(str)
let data = str.Split('|')
where data.Length == 2
select new Person { Age = Int32.Parse(data[0], NumberStyles.Integer, CultureInfo.CurrentCulture), Name = data[1] };
results is now IEnumerable<Person> which you can do ToList or ToArray on to get a List<Person> or Person[], or you can simply use the results with a foreach loop.
UPDATE: here is the Person class needed to make this more functional.
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
You could do something like this. (There is no error checking, you might want to check for errors when parsing the age etc.
class Person
{
string Name {get;set;}
int Age {get;set;}
}
List<Person> people = new List<Person>();
string line;
using (StreamReader sr = new StreamReader(path))
{
sr.ReadLine();
while ((line == sr.ReadLine()) != null)
{
string[] channels = line.Split('|');
people.Add(new Person() {Age=int.Parse(channels[0]), Name=channels[1]});
}
}
You should use Dictionary and not Array to store the data.
Sample code:
FileStream fs = new FileStream("filename");
Dictionary<int,string> dict = new Dictionary<int,string>();
string line = "";
fs.ReadLine(); //skip the first line
while( (line = fs.ReadLine()) != null)
{
string parts = line.split("|".ToCharArray());
dict.Add(int.Parse(parts[0]), parts[1]);
}

Categories