How to Append Data to a Text File in a Windows Forms Application?

Cenk 1,021 Reputation points
2024-12-21T19:15:40.1266667+00:00

In a Windows Forms application, data is read from a text file and displayed in a list box. The goal is to add a new item from a textbox to the same text file when a button is pressed, but the item is not being appended to the file as expected.

The button click event code is as follows:

private void btnAdd_Click(object sender, EventArgs e)
{
    string newItem = txtNewItem.Text.Trim(); // Get the new item from the TextBox
    if (!string.IsNullOrWhiteSpace(newItem))
    {
        listBoxFirmalar.Items.Add(newItem); // Add to the ListBox
        // Use StreamWriter to append the new item to the file
        try
        {
            using (StreamWriter writer = new StreamWriter(filePath, true, Encoding.UTF8)) // 'true' for appending
            {
                writer.WriteLine(newItem); // Write the new item to the file
            }
            MessageBox.Show("Item added to file successfully."); // Confirm success
        }
        catch (Exception ex)
        {
            MessageBox.Show($"Error writing to file: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        txtNewItem.Clear(); // Clear the input field
    }
    else
    {
        MessageBox.Show("Please enter a valid item.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,914 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,152 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Cenk 1,021 Reputation points
    2024-12-23T06:19:26.5933333+00:00

    solved:

    private readonly string filePath = Path.Combine(Application.StartupPath +"Data", "test.txt");
    
    0 comments No comments

  2. Karen Payne MVP 35,461 Reputation points
    2024-12-23T11:16:33.8466667+00:00

    Consider the following extension methods to load/save to a unbound ListBox.

    namespace WinFormsListBoxApp.Classes;
    
    using System.Windows.Forms;
    
    /// <summary>
    /// Provides extension methods for the <see cref="ListBox.ObjectCollection"/> class,
    /// enabling additional functionality such as saving to and loading from files.
    /// </summary>
    /// <remarks>
    /// No exception handling provided as each developer may have different requirements like, log or other actions.
    /// </remarks>
    public static class ListBoxExtensions
    {
        /// <summary>
        /// Saves the contents of the <see cref="ListBox.ObjectCollection"/> to a specified file.
        /// </summary>
        /// <param name="sender">The <see cref="ListBox.ObjectCollection"/> containing the items to save.</param>
        /// <param name="fileName">The path of the file where the contents will be saved.</param>
        /// <remarks>
        /// Each item in the collection is written as a separate line in the file.
        /// </remarks>
        public static void SaveToFile(this ListBox.ObjectCollection sender, string fileName)
        {
            File.WriteAllLines(fileName, sender.Cast<string>().Select(line => line).ToArray());
        }
    
        /// <summary>
        /// Loads the contents of a specified file into the <see cref="ListBox.ObjectCollection"/>.
        /// </summary>
        /// <param name="sender">The <see cref="ListBox.ObjectCollection"/> where the file contents will be loaded.</param>
        /// <param name="fileName">The path of the file to load the contents from.</param>
        /// <remarks>
        /// If the specified file does not exist, the method does nothing.
        /// Each line in the file is added as a separate item in the collection.
        /// </remarks>
        public static void LoadFromFile(this ListBox.ObjectCollection sender, string fileName)
        {
            if (!File.Exists(fileName)) return;
            sender.Clear();
            sender.AddRange(File.ReadAllLines(fileName).Cast<object>().ToArray());
        }
    }
    

    Form code

    using Bogus;
    using WinFormsListBoxApp.Classes;
    
    namespace WinFormsListBoxApp;
    
    public partial class Form1 : Form
    {
        private string _fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "companies.txt");
        public Form1()
        {
    
            InitializeComponent();
    
            if (!File.Exists(_fileName))
            {
                File.WriteAllLines(_fileName, new List<string>()
                {
                    "Microsoft",
                    "Apple"
                });
            }
    
            listBox1.Items.LoadFromFile(_fileName);
            listBox1.SelectedIndex = 0;
    
        }
    
        private void SaveButton_Click(object sender, EventArgs e)
        {
            var f = new Faker();
            listBox1.Items.Add(f.Company.CompanyName());
            listBox1.Items.SaveToFile(_fileName);
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
        }
    
        private void LoadButton_Click(object sender, EventArgs e)
        {
            listBox1.Items.LoadFromFile(_fileName);
        }
    
        private void FreshStartButton_Click(object sender, EventArgs e)
        {
            
            listBox1.Items.Clear();
    
            File.WriteAllLines(_fileName, new List<string>()
            {
                "Microsoft",
                "Apple"
            });
    
            listBox1.Items.LoadFromFile(_fileName);
            listBox1.SelectedIndex = 0;
    
        }
    }
    

    Full source found here.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.