Skip to main content
 首页 » 编程设计

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

2024年02月13日16wuhuacong

<分区>

我有一个加密的小电子邮件程序。以下只是该程序的摘要:

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(); 
    } 
} 

所以我现在遇到的问题是关于 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"); 
        } 
    } 
} 

因此,当单击发送按钮并且文件被加密并发送时,我想将其从我的计算机中删除。因此,我运行方法 deleteEncryptedFile 从我的计算机中删除 EncryptedFile.pgp。但我一直收到这条消息说:

"The process cannot access the file 'C:\EncryptedFile.pgp' because it is being used by another process."

但是我唯一能想到的“其他过程”就是加密方式(encryptAll())。但不应该这样做吗?请告诉我如何解决这个问题?