File in use while trying to add text to it

Andi 106 Reputation points
2023-04-27T09:59:38.67+00:00
I am trying to add a new line to a txt file by following program, problem is, that the ex.Message says that the file is already in use. Could this be because of the selection in the comboBox?
If so how can i change it.

Thanks :)




try
            {
                string[] files = Directory.GetFiles(@"C:\ProgramData\timerecording TechSupport\Items");
                foreach (string f in files)
                {
                    var fileItem = new FileItem { Title = Path.GetFileName(f), Path = Path.GetFullPath(f) };
                    comboBox6.Items.Add(fileItem);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            try
            {
                System.IO.File.AppendAllText(mainpath+"\\Items\\" + comboBox6.Text, "\n" + textBox7.Text);
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
        }
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,722 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.
9,421 questions
{count} votes

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 35,846 Reputation points
    2023-04-27T11:29:45.8366667+00:00

    .Message says that the file is already in use

    As the message says, to write to a text file you need exclusive access to. Other processes must close the file.

    0 comments No comments