create and save a file in windows forms application c# code example
Example 1: save text input into a txt file in c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TextWriter txt = new StreamWriter("C:\\demo\\demo.txt");
txt.Write(textBox1.Text);
txt.Close();
}
}
}
Example 2: c# export textbox data to text file github
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace A2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_selectpic_Click(object sender, EventArgs e)
{
string imagelocation = "";
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Select Your Profile Photo";
dialog.InitialDirectory = "c:\\Users\\docker\\Desktop";
dialog.Filter = "Images File (*.JPG;)|*.JPG;";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
imagelocation = dialog.FileName;
pb_profile.ImageLocation = imagelocation;
tb_url.Text = imagelocation;
}
}
catch (Exception)
{
MessageBox.Show("An Error Occured");
}
}
private void btn_Save_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Are you sure you want to save the profile", "confirmation", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
SaveFileDialog savefile = new SaveFileDialog();
savefile.RestoreDirectory = true;
savefile.InitialDirectory = "e:\\";
savefile.FileName = String.Format("{0}.txt", tb_name.Text);
savefile.DefaultExt = "*.txt*";
savefile.Filter = "TEXT Files|*.txt";
if (savefile.ShowDialog() == DialogResult.OK)
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(savefile.FileName))
sw.WriteLine("Name: " + tb_name.Text + "\r\n" + "Email: " + tb_email.Text + "\r\n" + "Age: " + nud_age.Text + "\r\n" + "Profile Photo: " + tb_url.Text);
}
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}