我有一个小型电子邮件程序,可以进行加密。以下是该计划的摘要:
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。但我一直在说这句话:
“进程无法访问文件'C:\ EncryptedFile.pgp',因为它正由另一个进程使用。”
但我能想到的唯一“其他过程”是加密方法(encryptAll())。但是不应该这样做吗?请告知我如何解决这个问题?
答案 0 :(得分:7)
尝试在删除过程之前处理邮件附件。
mailAttachment.Dispose();
答案 1 :(得分:-3)
在删除您的加密文件之前,您可以验证然后删除。以下功能可以帮助您查找文件是否被其他进程使用。
public static bool IsFileLocked(string fileName)
{
FileStream stream = null;
try
{
stream = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (stream != null)
stream.Close();
}
return false;
}