In: Computer Science
Create a new C# project in Visual Studio. The purpose of this application is to allow the user to open a data file of their choice and your program will retrieve the contents and display them in a ListBox on your Form. Your Form will need an ‘Open’ Button to begin the process, as well as an OpenFileDialog control to allow the user to pick a file of their choice. The OpenFileDialog control should start the user in their ‘C:\’ drive, and should be pre-filtered to only show text files (*.txt). You will also need a ListBox to display the file contents, and the usual Reset and Close Buttons. Be sure to test the application with your own text file. The file you generated in Assessment might be a good choice, but realize I will check it with my own file, which might hold more than just a series of numbers. Since you don’t know the contents of the file, or how many lines there are, make sure that your ListBox is wide enough to handle content as wide as 150 characters per line without horizontal scrolling, and that your file-reading code has the appropriate data validation to determine if the user picked a file or not, and to read *all* the contents of the chosen file, no matter how many lines there are, without going over the end of the file.
//C# code
using System;
using System.IO;
using System.Windows.Forms;
namespace read_filein_listbox
{
public partial class Form1 : Form
{
string fileName = "";
public Form1()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
//start the user in their ‘C:\’ drive,
openFileDialog1.InitialDirectory = @"C:\";
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Title = "Browse Files";
openFileDialog1.DefaultExt = ".txt";
//should be pre - filtered to only show text files(*.txt).
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files
(*.*)|*.*";
openFileDialog1.ShowDialog();
fileName = openFileDialog1.FileName;
try
{
StreamReader reader = new StreamReader(fileName);
while(!reader.EndOfStream)
{
listBox1.Items.Add(reader.ReadLine());
}
reader.Close();
}
catch(FileNotFoundException ex)
{
Console.WriteLine("File not found.");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnReset_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
fileName = "";
}
}
}
//Form design

//Output

//If you need any help regarding this solution ....... please leave a comment ...... thanks