-1

I'm a begginer programmer and I'm learning C#, I have a big difficulty with Files. Someone can help me with this, please?

I created a .txt file and I want to append text choosing the file location instead creating/saving in the startup path just like my code does.

This is what I have:

public void btnGuardar_Click(object sender, EventArgs e)
    {
        string caminho = Application.StartupPath + "ID_Cartões.txt";

        if (lblDEC.Text != "")
        {
            StreamWriter txt = File.AppendText(caminho);
            txt.WriteLine("ID: " + lblDEC.Text + "\r\n" + DateTime.UtcNow.ToString("dd/MM/yyyy HH:mm:ss") + "\r\n");
            txt.Close();

            MessageBox.Show("Ficheiro guardado com sucesso!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            MessageBox.Show("Hexadecimal não convertido.", "ERRO!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
Kalli
  • 1
  • 1
  • 1
    Use the `OpenFileDialog` as explained in this Q&A: [How to add browse file button to Windows Form using C#](https://stackoverflow.com/questions/4999734/how-to-add-browse-file-button-to-windows-form-using-c-sharp) – MindSwipe Feb 28 '22 at 15:46
  • If you are starting out, I would highly recommend learning to use a serialization library like [json.net](https://www.newtonsoft.com/json). This will likely simplify the process of storing and loading data from files or the network. – JonasH Feb 28 '22 at 15:47
  • @JonasH how is json related to this question? – Lei Yang Feb 28 '22 at 15:49
  • @Lei Yang, it is not, at least not directly. But whenever new programmers start with saving data they often go for StreamWriter or BinaryFormatter, and neither is great. A serialization library can greatly simplify the process of turning objects into data, and back again. But if you are new you might not be aware that such tools exist. – JonasH Feb 28 '22 at 15:55

2 Answers2

0

Winforms has a SaveFileDialog control where the user can choose the location and file name or a FolderBrowserDialog control where they can choose a folder and you specify the filename.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

You can use an OpenFileDialog, the FileName property contains the file path of the file selected by the user.

OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK) 
{ 
  string filePath = openFileDialog.FileName; 
} 
Simone D.
  • 1
  • 3
  • `using (var ofd = new OpenFileDialog()) { ... }` <- It's important that you dispose of it. – Jimi Feb 28 '22 at 16:41