How do I read a file into a list? - c#

I have a project to create a phone book of sorts. It needs to read a file and output the name to a list box in the main form. When the user selects a name a new form should open with the name phone number and email address.
Currently there are no syntax errors, but the program does not read the file. It always throws an exception. The file name is on my desktop and I verified the file name matches the code. Any insight on why this is happening would be appreciated.
Here is my code:
public partial class Form1 : Form
{
List<PersonEntry> nameList = new List<PersonEntry>();
public Form1()
{
InitializeComponent();
}
class PersonEntry
{
public string _name { get; set; }
public string _number { get; set; }
public string _email { get; set; }
}
private void GetNamesButton_Click(object sender, EventArgs e)
{
Readfile();
DisplayNameList();
}
private void Readfile()
{
try
{
StreamReader inputFile;
string line;
char[] deliminator = { ';' };
inputFile = File.OpenText("Personlist.txt");
while (!inputFile.EndOfStream)
{
//Use class
PersonEntry entry = new PersonEntry();
line = inputFile.ReadLine();
string[] tokens = line.Split(deliminator);
entry._name = tokens[0];
entry._number = tokens[1];
entry._email = tokens[2];
nameList.Add(entry);
}
}
catch
{
MessageBox.Show("Unable to open file");
}
}
private void DisplayNameList()
{
//Add the entry objects to the List
foreach (PersonEntry nameDisplay in nameList)
{
namesListBox.Items.Add(nameDisplay._name);
}
}
public void namesListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (namesListBox.SelectedIndex != -1)
{
//Get full info for the selected item in the list
string name = nameList[namesListBox.SelectedIndex]._name;
string email = nameList[namesListBox.SelectedIndex]._email;
string phone = nameList[namesListBox.SelectedIndex]._number;
//Create second form for these details
DetailForm f2 = new DetailForm(name, email, phone);
f2.ShowDialog();
}
else
{
MessageBox.Show("Please select a Name.");
}
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

File is not in correct folder, exception shows correct file location. After moving it the application works as intended.

Related

Listview in virtual mode - get list of selected items

There is a way to get all items selected with the mouse in a list view when virtual mode is enabled for this winform.
Example of an working code in use, I can retrieve only one selected file for now. Not too much examples finded on the web and could be identified as duplicate but is not conclusive for me, or the answer is to simple.
private void FilesFoundList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
try
{
if (e.ItemIndex >= 0 && e.ItemIndex < ListFilesInfos.Count)
{
try
{
var acc = ListFilesInfos[e.ItemIndex];
//with colors
e.Item = new ListViewItem(new string[] { acc.TagItem, acc.FileName, acc.FilePath.ToString() })
{ Tag = acc,
BackColor = SearchLabColor(0, Path.GetExtension(acc.FileName.ToString()), acc.FilePath.ToString(), acc.FileName.ToString()),
ForeColor = SearchLabColor(1, Path.GetExtension(acc.FileName.ToString()), acc.FilePath.ToString(), acc.FileName.ToString()),
UseItemStyleForSubItems = false
}; // Set Tag object property to our actual AccountInfo object
}
catch { this.Refresh(); }
}
}
catch
{
}
}
private void ShowItemsVirtual(List<SearchFilesInfo> infos)
{
try
{
FilesFoundList.VirtualListSize = infos.Count; // Set number of items in list view
}
catch { this.Refresh(); }
}
private void FilesFoundList_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
SelectedFiles.GlobalVar = (e.Item.SubItems[2]).Text.ToString() + (e.Item.SubItems[1]).Text.ToString();
}
}
You could abbreviate your code to:
List<multiSearchSelect> multiSearchSelect = new List<multiSearchSelect>();
private void FilesFoundList_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
multiSearchSelect=
FilesFoundList.SelectedIndices
.Select(i=> new multiSearchSelect()
{
fileName = FilesFoundList.Items[i].SubItems[1].Text,
filePath = FilesFoundList.Items[item].SubItems[2].Text
});
}
}
class multiSearchSelect
{
public string fileName { set; get; }
public string filePath { set; get; }
}
I will post my solution that fits to my purpose. I have added ItemsSelectionRangeChanged event and get the list of file selected.
List<multiSearchSelect> multiSearchSelect = new List<multiSearchSelect>();
private void FilesFoundList_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
multiSearchSelect.Clear();
ListView.SelectedIndexCollection col = FilesFoundList.SelectedIndices;
if (col.Count > 1)
{
foreach (int item in col)
{
multiSearchSelect.Add(new multiSearchSelect
{
fileName = FilesFoundList.Items[item].SubItems[1].Text,
filePath = FilesFoundList.Items[item].SubItems[2].Text
});
}
}
}
}
class multiSearchSelect
{
public string fileName { set; get; }
public string filePath { set; get; }
}

How do I join the selected items in multiple list boxes with the user text entered in text box in c#?

Goal:Is to display Project name, formed by joining list box selected items with user entered text in the text box and display it as a label.
Description: I am creating a windows for App, which has two listboxes displaying Firstname-lbA & Lastname- lbB along with a textbox for the user to enter packet name.
For example: If I select an item(first name)from the listbox A i.e. "XXX", select an item(last name)from the listbox B i.e. "YYY" and enter text in the Textbox i.e. "PKT-100" & click create button I would want to display the Project name as XXX-YYY-PKT-100.
checking conditions:
If no Item in lbA is selected then display:YYY-PKT-100.
If no Item in Lb B is seleected then display :XXX-PKT-100.
If no Text is entered the display: XXX-YYY.
No spaces/double dashes are allowed.
I'd really appreciate if someone could help me with your suggestions.
Thanks!!
Code:
FirstNamespace Project
{
public partial class ProjectTool : Form
{
public List<FirstName> ltfirstname { get; set; }
public List<LastName> ltlastname { get; set; }
public FirstName SelectedFirstname => (FirstName)lbGetFirstName.SelectedItem
public LastName SelectedLastname => (LastName)lbGetLastName.SelectedItem;
public projecTool()
{
InitializeComponent();
ltfirstname = GetFirstNames();
lbGetFirstName.DataSource = ltfirstname;
ltlastname = GetLastNames();
lbGetLastName.DataSource = ltlastname;
}
public List<FirstName> GetFirstNames()
{
List<FirstName> fnames = new List<FirstName>();
using (StreamReader sr = new StreamReader("D:\\FirstNames.csv"))
{
string line;
try
{
while ((line = sr.ReadLine()) != null)
{
string[] columns = line.Replace("\"","").Split(',');
if (columns.Length >= 1)
{
var name = new FirstName();
name.FirstName = columns[0];
fnames.Add(name);
}
}
}
catch (Exception ex) { }
return fnames;
}
}
public List<LastName> GetlastNames()
{
List<LastName> lnames = new List<LastName>();
using (StreamReader sr = new StreamReader("D:\\LastNames.csv"))
{
string line;
try
{
while ((line = sr.ReadLine()) != null)
{
string[] columns = line.Replace("\"","").Split(',');
if (columns.Length >= 1)
{
var lname = new LastName();
lname.LastName = columns[0];
lnames.Add(lname);
}
}
}
catch (Exception ex) { }
return lnames;
}
}
public void CreateprojectName()
{
// Create project name as Firstname-Lastname-Packetname
//if project name already exists then check for correctness/update.
// Check -> if there are double dashes/spaces in the Project name
}
private void lbGetFirstName_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void lbGetlastName_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void txtPacketName_TextChanged(object sender, EventArgs e)
{
}
private void create_projectname_button1_Click(object sender, EventArgs e)
{
}
}
}
Its quite simple for listBox use SelectedItem & for textBox use Text property.
private void create_projectname_button1_Click(object sender, EventArgs e)
{
if (lbGetFirstName.SelectedItems.Count==0)
{
label1.Text = "YYY-PKT-100";
}
if (lbGetlastName.SelectedItems.Count==0)
{
label1.Text = "XXX-PKT-100";
}
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
label1.Text = "XXX-YYY";
}
else
{
label1.Text = lbGetFirstName.SelectedItem + "-" + listBox2.SelectedItem + "-" + lbGetlastName.Text;
}
}

Saving keeps overwriting itself C#

I am making an application which will save and load products. These products have three properties of a product name, customer name and firmware location. However, when I try to save them, it will only save one and keeps overwriting with the most recent product saved. The following is my code for the product class:
public class Product
{
//private product data
private string productName;
public string getProductName()
{
return this.productName;
}
public void setProductName (string inProductName)
{
this.productName = inProductName;
}
private string customerName;
public string getCustomerName()
{
return this.customerName;
}
public void setCustomerName (string inCustomerName)
{
this.customerName = inCustomerName;
}
private string firmwareLocation;
public string getFirmwareLocation()
{
return this.firmwareLocation;
}
public void setFirmwareLocation (string inFirmwareLocation)
{
this.firmwareLocation = inFirmwareLocation;
}
//constructor
public Product (string inProductName, string inCustomerName, string inFirmwareLocation)
{
productName = inProductName;
customerName = inCustomerName;
firmwareLocation = inFirmwareLocation;
}
//save method
public void Save (System.IO.TextWriter textOut)
{
textOut.WriteLine(productName);
textOut.WriteLine(customerName);
textOut.WriteLine(firmwareLocation);
}
public bool Save (string filename)
{
System.IO.TextWriter textOut = null;
try
{
textOut = new System.IO.StreamWriter(filename);
Save(textOut);
}
catch
{
return false;
}
finally
{
if (textOut != null)
{
textOut.Close();
}
}
return true;
}
At the end is my save methods.
Here is the code for when the user presses the add product button:
private void Add_Click(object sender, RoutedEventArgs e)
{
//get input from user
string inputCustomerName = customerNameTextBox.Text;
string inputProductName = productNameTextBox.Text;
string inputFirmwareLocation = firmwareTextBox.Text;
try
{
Product newProduct = new Product(inputProductName, inputCustomerName, inputFirmwareLocation);
newProduct.Save("products.txt");
MessageBox.Show("Product added");
}
catch
{
MessageBox.Show("Product could not be added");
}
}
You are not appending the text to your file, thats why it keeps overwriting the last entry over and over again.
Try to change your save method to:
public bool Save (string filename)
{
System.IO.TextWriter textOut = null;
try
{
textOut = new System.IO.StreamWriter(filename, true);
Save(textOut);
}
catch
{
return false;
}
finally
{
if (textOut != null)
{
textOut.Close();
}
}
return true;
}
Notice the "true" as the second parameter in the StreamWriter constructor. This tells the StreamWriter to append the new line.

Writing List items to text file c#

I am trying to get a List to save into a text file and am running into a problem.
It will save into the text file but not all the information as needed but only the information that actually shows in the ListBox. Suggestions?
namespace Employee_Form
{
public partial class frmMain : Form
{
FileStream output;
StreamReader fileReader;
//StreamWriter fileWriter;
List<Employee> employeeList = new List<Employee>();
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFile();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveAs();
}
private void addNewToolStripMenuItem_Click(object sender, EventArgs e)
{
PropertiesOpen();
}
private void PropertiesOpen()
{
//creates an instance of the Properties Form
frmProperties myform = new frmProperties();
DialogResult result = myform.ShowDialog();
}
//Opens a file chosen by a user and places information into the listbox
private void OpenFile()
{
OpenFileDialog fileChooser = new OpenFileDialog();
fileChooser.Title = "Pick a file";
fileChooser.Filter = "Text Files (*.txt) | *.txt";
DialogResult result = fileChooser.ShowDialog();
//
if (result == DialogResult.Cancel)
{
//do nothing
return;
}
string strFileName = fileChooser.FileName;
try
{
//open the file for read access
output = new FileStream(strFileName, FileMode.Open, FileAccess.Read);
fileReader = new StreamReader(output);
//variables to hold read record
string strInputLine;
string[] fields;
//loop to get records and break into fields
while (fileReader.EndOfStream != true)
{
//read record
strInputLine = fileReader.ReadLine();
//split the records when read
fields = strInputLine.Split(',');
//add records to the list box
employeeList.Add(new Employee(fields[1], fields[0], fields[2],
Convert.ToDouble(fields[3])));
}
lstRecords.DataSource = employeeList;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//closes fileReader and output to save Resources
fileReader.Close();
output.Close();
}
}
public void SaveAs()
{
//create a file dialog
SaveFileDialog fileChooser = new SaveFileDialog();
fileChooser.Title = "Choose A Save Location";
fileChooser.Filter = "Text Files (*txt)|*.txt";
//open the dialog and get a result
DialogResult result = fileChooser.ShowDialog();
//checks if user clicks cancel
if (result == DialogResult.Cancel)
{
return;
}
//get the file name from the dialog
string strFileName = fileChooser.FileName;
try
{
//open the new file for write access
StreamWriter SaveFile = new StreamWriter(strFileName);
foreach (var item in employeeList)
{
SaveFile.WriteLine(item.ToString());
}
SaveFile.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//close resources
//fileWriter.Close();
output.Close();
}
}
}
Sorry, I am new to this. There are two forms and the second one is for editing/adding new employees. only need to show the first and last name in the ListBox. Here is my Employee class also:
public class Employee
{
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public string EmpType
{
get;
set;
}
public double Salary
{
get;
set;
}
public Employee(string firstName, string lastName, string empType, double salary)
{
FirstName = firstName;
LastName = lastName;
EmpType = empType;
Salary = salary;
}
public override string ToString()
{
return string.Format("{0}, {1}", LastName, FirstName);
}
}
When you call SaveFile.WriteLine(item.ToString());, you're writing the result of the ToString() method of Employee:
return string.Format("{0}, {1}", LastName, FirstName);
This is the same method called by the ListBox to display the object in the list. So the behavior you're seeing is exactly what one would expect.
If you want to see something different, try something like this:
SaveFile.WriteLine(string.Format("{0}, {1}, {2}, {3}", item.LastName, item.FirstName, item.EmpType, item.Salary));
Use whatever properties and formatting you want in your file.

How do I load multiple XML files and read them?

I've a problem. In my code I'm looking for all xml files in one directory. Finally it works but I don't know how to read them. A single one is loaded with the string xmlFile. I think I need to replace or edit that in this way that my code now that xmlFile is not only one file, but all files who are found in the directory.
What should I be doing?
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
private const string xmlFile = "C:\Games\games.xml"; // single xml file works
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
this.LoadDataFromXml();
listView.Items.AddRange(Directory.GetFiles("C:\Games\", "*.xml")
.Select(f => new ListViewItem(f))
.ToArray());
}
private void LoadDataFromXml()
{
if (File.Exists(xmlFile))
{
XDocument document = XDocument.Load(xmlFile);
if (document.Root != null)
{
foreach (XElement gameElement in document.Root.Elements("game"))
{
string gamename = gameElement.Element("gamename").Value;
string launchpath = gameElement.Element("launchpath").Value;
string uninstallpath = gameElement.Element("uninstallpath").Value;
string publisher = gameElement.Element("publisher").Value;
// check if gameElement.Element(ELEMENTNAME) is not null
Game game = new Game(gamename, launchpath, uninstallpath, publisher);
AddGameToListView(game);
}
}
}
}
private void AddGameToListView(Game game)
{
ListViewItem item = CreateGameListViewItem(game);
this.listView.Items.Add(item);
}
private ListViewItem CreateGameListViewItem(Game game)
{
ListViewItem item = new ListViewItem(game.Gamename);
item.SubItems.Add(game.Launchpath);
item.SubItems.Add(game.Uninstallpath);
item.SubItems.Add(game.Publisher);
item.Tag = game;
return item;
}
private void InitializeListView()
{
this.listView.View = View.Details;
this.listView.GridLines = true;
this.listView.MultiSelect = false;
this.listView.FullRowSelect = true;
this.listView.Columns.AddRange(new[]
{
new ColumnHeader{Text = "Gamename", Width = 200},
new ColumnHeader{Text = "Launchpath"},
new ColumnHeader{Text = "Uninstallpath"},
new ColumnHeader{Text = "Publisher"}
});
this.listView.MouseDoubleClick += ListViewOnMouseDoubleClick;
}
private void ListViewOnMouseDoubleClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && this.listView.SelectedItems.Count > 0)
{
Game game = (Game)((this.listView.SelectedItems[0].Tag);
try
{
Process.Start(game.Launchpath);
}
catch (Exception ex)
{
MessageBox.Show("Can not start game.\nDetails:\n" + ex.Message, "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}
internal class Game
{
public Game()
{
}
public Game(string gamename, string launchpath, string uninstallpath, string publisher)
{
this.Gamename = gamename;
this.Launchpath = launchpath;
this.Uninstallpath = uninstallpath;
this.Publisher = publisher;
}
public string Gamename { get; set; }
public string Launchpath { get; set; }
public string Uninstallpath { get; set; }
public string Publisher { get; set; }
}
}
UPDATE:
This is my current code. how can i send f to LoadDataFromXml ?
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
this.Height = Screen.PrimaryScreen.WorkingArea.Height;
var files = Directory.GetFiles(#"C:\Games\", "*.xml").Select(f => new ListViewItem(f)).ToArray(); listView.Items.AddRange(files);
foreach (var f in files)
{
this.LoadDataFromXml(f);
}
}
private void LoadDataFromXml(//What Do I need to enter here?)
{
foreach (XElement gameElement in f.Root.Elements("game"))
{
string gamename = gameElement.Element("gamename").Value;
string launchpath = gameElement.Element("launchpath").Value;
string portablesave = gameElement.Element("portablesave").Value;
string publisher = gameElement.Element("publisher").Value;
string gameid = gameElement.Element("gameID").Value;
string update = gameElement.Element("update").Value;
// check if gameElement.Element(ELEMENTNAME) is not null
Game game = new Game(gamename, launchpath, portablesave, publisher, gameid, update);
AddGameToListView(game);
}
}
Simple use Directory functions to get all your XML files, and loop through them, by calling LoadDataFromXml for each file. Note: You will need to refactor your code a little bit.
You need to modify your LoadDataFromXml to take file as a parameter. And change your Form1 constructor to something like this
public Form1()
{
this.InitializeComponent();
this.InitializeListView();
var files = Directory.GetFiles("C:\Games\", "*.xml")
.Select(f => new ListViewItem(f))
.ToArray();
listView.Items.AddRange(files);
foreach(var f in files)
{
this.LoadDataFromXml(f);
}
}

Categories

Resources