In this example, we will learn how to delete a selected file with OpenFileDialog.
An OpenFileDialog control is used to browse and select a file on a computer. We can create an OpenFileDialog control using a Forms designer at design-time or using the OpenFileDialog class in code at run-time (also known as dynamically).
Form Design:
Source Code:
1 2 3 | using System.IO; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | namespace delete_file { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.Text = "csharp-console-examples.com"; this.BackColor = Color.Orange; textBox1.Enabled = false; } string destinationFile = ""; private void button1_Click(object sender, EventArgs e) //Browse { openFileDialog1.FileName = ""; if (openFileDialog1.ShowDialog() == DialogResult.OK) { destinationFile = openFileDialog1.FileName.ToString(); textBox1.Text = destinationFile; } else { MessageBox.Show("Select File...", "Warning..!", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void button2_Click(object sender, EventArgs e)//Delete { try { File.Delete(destinationFile); destinationFile = ""; textBox1.Text = ""; } catch(Exception ex) { MessageBox.Show(ex.ToString()); } } } } |
Output: