My project stores phone numbers into a list<> and saves them into a .bin file:
private void savebutton_Click(object sender, EventArgs e)
{
SaveFileDialog sv = new SaveFileDialog();
sv.Filter = "Binary files (*.bin)|*.bin|All files(*.*)|*.*";
sv.Title = "Save File";
sv.FilterIndex = 2;
sv.RestoreDirectory = true;
sv.InitialDirectory = Path.GetFullPath(@"F:\Computer Technology Skills\Programming 35\Module 1\ICA10\ICA10\bin\Debug");
if (sv.ShowDialog() == DialogResult.OK)
{
try
{
FileStream fs = new FileStream(sv.FileName, FileMode.Create, FileAccess.Write);
BinaryWriter file = new BinaryWriter(fs);
// System.IO.StreamWriter file = new System.IO.StreamWriter(sv.FileName.ToString());
var message = string.Join(Environment.NewLine, PhoneNum);
file.Write(message);
file.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Then pressing the load button is supposed to delete the items currently in the listbox1 to replace them with whatever items were in the bin file on each line.
private void loadbutton_Click(object sender, EventArgs e)
{
OpenFileDialog od = new OpenFileDialog();
string databyte = null;
long iNumInts = 0;
od.RestoreDirectory = true;
od.InitialDirectory = Path.GetFullPath(@"F:\Computer Technology Skills\Programming 35\Module 1\ICA10\ICA10\bin\Debug");
if (od.ShowDialog() == DialogResult.OK)
{
try
{
FileStream fs = new FileStream(od.FileName, FileMode.Open);
listBox1.Items.Clear();
using (BinaryReader reader = new BinaryReader(fs))
{
iNumInts = fs.Length / sizeof(int);
for (int i = 0; i < iNumInts; i++)
{
databyte = reader.ReadString(); //Endofstreamexception
listBox1.Items.Add(databyte);
}
fs.Close();
reader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The problem is, when I load the file I saved, the items are all stuck on the first index of the listbox1 and I receive an endofstream exception.
I'm a bit confused here since my notes didn't help much and other stack overflow questions I found were examples using integers or arrays. I switched from streamwriter to binarywriter which helped a lot, but any help would be much appreciated!
I would recommend using the StreamReader
for this.
using (StreamReader reader = new StreamReader(od.Filename))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
listbox1.Items.Add(line);
}
}
You can also use File.ReadLines which does it all for you (if you're using .NET 4 or above).