// https://www.youtube.com/watch?v=0hNJWIDIQ7I
public partial class FileOpenSave : Form
{
public FileOpenSave()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog();
string defaultPath = Application.StartupPath + "\\Data";
openDialog.Filter = "text File|*.txt|All Files|*.*";
openDialog.InitialDirectory = defaultPath;
if(!Directory.Exists(defaultPath))
Directory.CreateDirectory(defaultPath);
try
{
if(openDialog.ShowDialog()==DialogResult.OK)
label1.Text = openDialog.FileName;
else
return ;
}
catch(System.Exception ex)
{
label1.Text = ex.Message;
return ;
}
textBox1.Text = "";
/*
// method 1
// Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader(openDialog.FileName);
string line = sr.ReadLine(); //Read the first line of text
while(line!=null)
{
textBox1.Text += (line+"\r\n");
line = sr.ReadLine(); // Read the next line
}
sr.Close();
*/
// method 2
string[] lines = System.IO.File.ReadAllLines(openDialog.FileName);
foreach(string line in lines)
textBox1.Text += (line+"\r\n");
}
private void button2_Click(object sender, EventArgs e)
{
if(label1.Text=="") return ;
/*
// method1
try
{
StreamWriter sw = new StreamWriter(label1.Text);
sw.Write(textBox1.Text);
sw.Close(); // close the file
MessageBox.Show("File Save Done");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
*/
// method 2
try
{
System.IO.File.WriteAllText(label1.Text, textBox1.Text);
MessageBox.Show("File Save Done!");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button3_Click(object sender, EventArgs e)
{ // Save As
SaveFileDialog saveDialog = new SaveFileDialog();
try
{
if(saveDialog.ShowDialog()==DialogResult.OK)
label1.Text = saveDialog.FileName;
}
catch(System.Exception ex)
{
label1.Text = ex.Message;
return ;
}
button2_Click(null, null);
}
}