Search code examples
c#windowswinformsfile-writing

System.IO.IOException creating File


I have an Error if I write something in a newly created File.

This is my code:

private void ButtonClick(object sender, EventArgs e)
    {                    
        Button b = (Button)sender;
        string inputKey = b.Text;

        for (int i = 0; i < tunes.Length; i++) 
        {
            if (b.Text == tun[i].TuneName)
            {
                Console.Beep(tun[i].Frequency, 200);
                Input.Items.Add(b.Text);
                Output.Items.Add(tun[i].TuneName);
                if (startButtonPressed == true)
                {
                    filename2 = musicFileName + ".csv";

                    File.WriteAllText(filename2, tun[i].TuneName);
                    RecordList.Items.Add(tun[i].TuneName);
                }
            }
        }           
    }

The Error comes at Line : File.WriteAllText()... It says that the File can not be used, because it's used by an another process,but I havent opened any File.


Solution

  • I'd use a Filestream generated by File.Create(), but I'd make the loop inside the using statement, so you ensure that all ressources will be released at the end (that's why you use using).

            using (FileStream fs = File.Create(Path.Combine(musicFileName, ".csv")))
            {
                foreach (tun in tunes)
                {
                    fs.Write(tun.TuneName);
                }
            }
    

    The problem you were actually having is, that you were never closing your file. You should look up using-keyword. It can used only with classes implementing the IDisponsable Interface. It then will call disponse() at the end of the using block and all ressources will be released, eg the file will be closed.