File in use while trying to add text to it

Andi 111 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");
            }
        }
Developer technologies | Windows Forms
Developer technologies | C#
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2023-04-27T10:47:58.72+00:00

    First remove the \n which most likely the issue

    Second use Path.Combine

    Other than the above, make sure another program does not have the file open.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 47,436 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

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.