Como criar e deletar arquivos no C#
Problema do aluno: Trabalho com Visual Studio 2005 (C#) e preciso apagar um arquivo quando eu clicar sobre um botão. Como faço?
Solução: Abrimos um projeto chamado ExemploArquivos, do tipo Windows Application no Visual Studio 2005 e posicionamos 5 buttons no formulário, como abaixo:
Tratamos o evento clique para cada botão. O código final fica assim:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
//
namespace ExemploArquivos
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = “ARQUIVOS TEXTO|*.txt”;
if (sfd.ShowDialog() == DialogResult.OK)
{
FileInfo arquivo = new FileInfo(sfd.FileName);
arquivo.Create();
MessageBox.Show(“Criei o arquivo”);
}
}
//
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = “ARQUIVOS TEXTO|*.txt”;
if (ofd.ShowDialog() == DialogResult.OK)
{
FileInfo arquivo = new FileInfo(ofd.FileName);
StreamWriter x = arquivo.CreateText();
x.WriteLine(“agnaldo”);
x.WriteLine(“50MINUTOS”);
x.WriteLine(x.NewLine);
x.Flush();
x.Close();
MessageBox.Show(“Acrescentei linhas ao arquivo”);
}
}
//
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = “ARQUIVOS TEXTO|*.txt”;
if (ofd.ShowDialog() == DialogResult.OK)
System.Diagnostics.Process.Start(ofd.FileName);
}
//
private void button4_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = “ARQUIVOS TEXTO|*.txt”;
if (ofd.ShowDialog() == DialogResult.OK)
System.Diagnostics.Process.Start(“iexplore.exe”, ofd.FileName);
}
//
private void button5_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = “ARQUIVOS TEXTO|*.txt”;
if (ofd.ShowDialog() == DialogResult.OK)
{
FileInfo arquivo = new FileInfo(ofd.FileName);
arquivo.Delete();
MessageBox.Show(“Deletei o arquivo”);
}
}
}
}