IOException: Sharing violation when trying to File.Delete

I’ve been working on a simple review system on a project, part of which involves sending a file in an e-mail which I can then reopen to see what the review was about (as that way I can also use it for debugging). So far I can send e-mails with files attached to them, I can download and reopen the files that were sent from the review system, but I would like to be able to rename the file before the review system sends it via e-mail so that when I download, I don’t have to go around renaming all the files. I thought I could do this by creating a copy of the file with the name I want, sending the file, and then deleting the file I’ve sent. Here’s my relevant code so far:

public void SendMail()
    {
        if (timer <= 0)
        {
            if (emailOfMessenger == "")
            {
                emailOfMessenger = "[User has not entered a e-mail]";
            }
            // @ signals newline
            body = "User '" + nameOfMessenger + "' has sent you a message - @ '" + messageOfMessenger + "' @ - Reply to them using the e-mail '" + emailOfMessenger + "'.";
            body = body.Replace("@", System.Environment.NewLine);

            mail.From = new MailAddress(to);
            mail.To.Add(to);
            mail.Subject = subject;
            mail.Body = body;

            string fileName = nameOfMessenger;

            if(File.Exists(Application.persistentDataPath + "/" + fileName + ".chs"))
                File.Delete(Application.persistentDataPath + "/" + fileName + ".chs");

            File.Copy(Application.persistentDataPath + "/savedGames.chs", Application.persistentDataPath + "/" + fileName + ".chs");
            mail.Attachments.Add(new Attachment(Application.persistentDataPath + "/" + fileName + ".chs"));            

            SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
            smtpServer.Port = 587;
            smtpServer.Credentials = new System.Net.NetworkCredential(to, password) as ICredentialsByHost;
            smtpServer.EnableSsl = true;
            ServicePointManager.ServerCertificateValidationCallback =
                delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                { return true; };
            smtpServer.Send(mail);
            
            timer = 300;
            File.Delete(Application.persistentDataPath + "/" + fileName + ".chs");
        }
    }

The only problem is that when I try deleting the file on the last line ( File.Delete(Application… ) I get the following error (the error is caused by trying to delete the file, it tells me in the error, I just haven’t put the whole error in here because this is the only relevant bit and it’s quite long :slight_smile: )

IOException: Sharing violation on path C:/Users/gharc/AppData/LocalLow/Gooey/3D Chess/Gooey.chs... etc.

I’ve had a look around and it appears to me like this error occurs when the file hasn’t been closed… But as far as I know (this is my first time using File.Copy and File.Delete) the file hasn’t been opened.
Any help would be great, either fixing the problem or working around it :slight_smile:

But as far as I know […] the file
hasn’t been opened.

Uhm you pass the filename to the Attachment that you add to your mail. So the file has to be opened in order to read the content.

Why do you actually copy the file? It seems all you want to do is using the file content as attachment. In that case you can simply pass the filestream or a memory copy of the content to the Attachment constructor.

using(var stream = File.Open(Application.persistentDataPath + "/savedGames.chs", FileMode.Open))
{
    mail.Attachments.Add(new Attachment(stream, fileName));
    //[...]
    smtpServer.Send(mail);
}