Reputation: 139
I'm working on Winform app that takes employees data as an array of 4 elements and correctly save these data to a text file in one line WITH SEPARATOR (",")..
My question is how to make it load any lines data and recognize the separator (",") so that I can get it to read all data by the first item which is name?
public partial class Form1 : Form
{
string[] data = new string[4];
string name;
string job;
string salary;
string join;
#region Save
void save()
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "")
{
MessageBox.Show("Please Fill All Fields", "error");
}
FileStream file = new FileStream("info.txt", FileMode.Append, FileAccess.Write);
StreamWriter wr = new StreamWriter(file);
wr.WriteLine(String.Join(",", data));
wr.Flush();
wr.Close();
comboBox1.Items.Add(data[0]);
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
}
#endregion
#region Search
void search()
{
FileStream file = new FileStream("info.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
sr.ReadLine(string.//what should i do here?
string[] lines = File.ReadAllLines("info.txt");
data[0].CompareTo(comboBox1.SelectedItem);
sr.ReadLine();
if (data[0] == name)
{
textBox1.Text = (data[0]);
textBox2.Text = (data[1]);
textBox3.Text = (data[2]);
textBox4.Text = (data[3]);
}
}
#endregion
Upvotes: 1
Views: 6738
Reputation: 2198
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,
string key, string def, StringBuilder retVal,
int size, string filePath);
/// <summary>
/// read value from given section and key
/// </summary>
/// <param name="Section">string</param>
/// <param name="Key">string</param>
/// <returns>string</returns>
public string IniReadValue(string Section, string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp,
255, this.path);
return temp.ToString();
}
To call this function See Below Code
string[] sBENCHNO=new Strin[256];
sBENCHNO = ini.IniReadValue("Sextion", "Key");
Upvotes: 0
Reputation: 139
Finally worked , line split in to array data , each added in the right text box :
void search()
{
FileStream file = new FileStream("info.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
sr.ReadLine();
var textLines = File.ReadAllLines("info.txt");
foreach (var line in textLines)
{
string[] dataArray = line.Split(',');
dataArray[0].CompareTo(comboBox1.SelectedItem);
if (dataArray[0] == comboBox1.SelectedItem.ToString())
{
textBox1.Text = (dataArray[0]);
textBox2.Text = (dataArray[1]);
textBox3.Text = (dataArray[2]);
textBox4.Text = (dataArray[3]);
}
}
}
Thanks alot mr.Jun Wei Lee
Upvotes: 1
Reputation: 1022
You can simply read the file back again, and use Split on the delimiter you have chosen
var textLines = File.ReadAllLines("");
foreach (var line in textLines)
{
string[] dataArray = line.Split(',');
}
Upvotes: 3