Automatically write to a default folder C #

2

Can someone tell me the C # method to write a document to a default folder under Code? In this case I wanted the program to automatically write to the Desktop.

This is the code I currently have on the button, but I intend to do it in Load.

 private void button1_Click(object sender, EventArgs e)
    {
      SaveFileDialog salvar = new SaveFileDialog();
        salvar.Filter = "Ficheiro de Configuração|*.cnf";
        salvar.DefaultExt = "txt";
        DialogResult salvou = salvar.ShowDialog();
        if (salvou == DialogResult.OK)
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(salvar.FileName);
                sw.WriteLine(txtConfig.Text);
                MessageBox.Show("Gravado com Sucesso!", "Sucesso",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information);
            }
            catch (IOException ex)
            {
                MessageBox.Show("IOException:\r\n\r\n" + ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception : \r\n\r\n" + ex.Message);
            }
            finally
            {
                if (sw != null)
                    sw.Close();
            }
            this.Close();
        }
 }

Cumps

    
asked by anonymous 15.05.2015 / 17:24

1 answer

1

In its function associated with the event FormLoad :

private void YourForm_Load(object sender, EventArgs e)
{
    var folder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    var fileName = Path.Combine(folder, "NomeFixoDoArquivo.cnf");

    File.WriteAllText(fileName, txtConfig.Text);
}

Environment.SpecialFolder.Desktop is one of the ways to recover the logged-in user's desktop folder.

File.WriteAllText(fileName, txtConfig.Text) allows you to write all the contents of the file at one time.

    
15.05.2015 / 17:48