Q:

C# - System.IO.IOException

I have a method that saves the text from a text box into a txt file but I get an System.IO.IOException error every time I back out of the SaveFileDialog.
    static OpenFileDialog ofd = new OpenFileDialog();
    static SaveFileDialog sfd = new SaveFileDialog();
    static String cp;

    private void SaveClass() {
        sfd.DefaultExt = "txt";
        sfd.Filter = "Text Files | *.txt";
        if (sfd.ShowDialog() == DialogResult.OK) {
            cp = sfd.FileName;
            File.Create(cp);

            File.WriteAllLines(@cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));

        }
    }

Visual Studio highlights the code that starts with "File.WriteAllLines" and says that's where I'm getting the error. Thanks.
Exact error message:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\ktfjulien\Documents\poop.txt' because it is being used by another process.
EDIT:
Thank you, I no longer get the error message but everything I save into the text box is written onto one line, regardless if the text is delimited by new lines or not.

A:

You do not need to do File.Create(cp); to write to a file. This is the cause of the error. Instead, directly do:
cp = sfd.FileName;
FileStream fs = File.OpenWrite(cp);

And if you want to use the StreamWriter instead of FileStream, use the FileStream as the input for your StreamWriter
StreamWriter sw = new StreamWriter(fs);

Or, you could also directly use File.WriteAllLines as you show - don't use the File.Create:
if (sfd.ShowDialog() == DialogResult.OK) {
    cp = sfd.FileName;
    //File.Create(cp); //remove this

    File.WriteAllLines(@cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));

}

