c#File.Delete - 另一个进程正在使用的文件

use*_*173 1 c# encryption process

我有一个小的电子邮件程序,它进行加密.以下只是该计划的摘要:

private void sendEmailButton_Click(object sender, EventArgs e)
{
    else
    {    
        //////////////////////////////////////////////////////////////////////////
        if (encryptEverythingCheckBox.Checked)
        {
            encryptAll();
        }
        //////////////////////////////////////////////////////////////////////////

        // Email credentials network codes blahblah
        // Assign the sender's email address to MailAddress function
        MailAddress mailAddress = new MailAddress(username);
        // Tells the recipent the sender's email
        mailMessage.From = mailAddress;
        // Username & Password of your email address
        System.Net.NetworkCredential networkCredential;
        networkCredential = new System.Net.NetworkCredential(username, password);
        // Enable SSL to encypt the connection
        smtpClient.EnableSsl = true;
        // Disable the use of default credentials
        smtpClient.UseDefaultCredentials = false;
        // Specify your own credential
        smtpClient.Credentials = networkCredential;
        //port number and send email blahblahblah
        deleteEncryptedFile();
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我现在遇到的问题是关于deleteEncryptedFile()和encryptAll()的void方法.以下是代码:

public void deleteEncryptedFile()
{
    if (File.Exists(@"C:\EncryptedFile.pgp"))            
        File.Delete(@"C:\EncryptedFile.pgp");            
}

public void encryptAll()
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.InitialDirectory = "c:\\";
    openFileDialog1.RestoreDirectory = true;
    openFileDialog1.Title = "CHOOSE RECIPENT'S PUBLIC KEY";

    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        invisibleTextBox.Text = openFileDialog1.FileName.ToString();
        string encryptedbodymessage = pgp.EncryptString(messageRichTextBox.Text, new FileInfo(@invisibleTextBox.Text));
        messageRichTextBox.Text = "";
        messageRichTextBox.Text = encryptedbodymessage;

        if (attachmentTextBox.Text != "")
        {
            bool asciiArmor = false;
            bool withIntegrityCheck = false;
            pgp.EncryptFile(@attachmentTextBox.Text, @invisibleTextBox.Text, @"C:\EncryptedFile.pgp", asciiArmor, withIntegrityCheck);
            invisibleTextBox.Text = "";
            mailAttachment = new Attachment(@"C:\EncryptedFile.pgp");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,当单击发送按钮并加密和发送文件时,我想将其从计算机中删除.所以我运行该方法deleteEncryptedFile从我的计算机中删除EncryptedFile.pgp.但我不断得到这样的信息:

"该进程无法访问文件'C:\ EncryptedFile.pgp',因为它正由另一个进程使用."

但我能想到的唯一"其他过程"是加密方法(encryptAll()).但是不应该这样做吗?请指教我如何解决这个问题?

小智 7

尝试在删除过程之前处理邮件附件.

mailAttachment.Dispose();
Run Code Online (Sandbox Code Playgroud)