我正在嘗試將位元組陣列寫入檔案并將其作為電子郵件發送。之后,我需要從保存的位置洗掉檔案。
但是在洗掉時,它會引發錯誤
“行程無法訪問檔案‘檔案路徑’,因為它正被另一個行程使用。”
根據File.WriteAllBytes() 檔案,它創建一個新檔案,將指定的位元組陣列寫入檔案,然后關閉檔案。如果目標檔案已經存在,它會被覆寫。請幫我找到解決方案。
string FolderPath = MyPath "PaySlips";
string filePath = FolderPath "/" userID "-PaySlip_" ddlMonth.SelectedItem.Text "_" ddlYear.SelectedItem.Text ".pdf";
if (!Directory.Exists(FolderPath))
{
Directory.CreateDirectory(FolderPath);
}
File.WriteAllBytes(filePath, bytes);
ArrayList attachments = new ArrayList();
attachments.Add(filePath);
SendEmail(emailID, cc, attachments);
if (File.Exists(attachments[0].ToString())) {
File.Delete(attachments[0].ToString()); //exception happens here
}
'''
uj5u.com熱心網友回復:
string FolderPath = MyPath "PaySlips";
string filePath = FolderPath "/" userID "-PaySlip_" ddlMonth.SelectedItem.Text "_" ddlYear.SelectedItem.Text ".pdf";
if (!Directory.Exists(FolderPath))
{
Directory.CreateDirectory(FolderPath);
}
File.WriteAllBytes(filePath, bytes);
File.Close();
File.Dispose();
ArrayList attachments = new ArrayList();
attachments.Add(filePath);
SendEmail(emailID, cc, attachments);
if (File.Exists(attachments[0].ToString())) {
File.Delete(attachments[0].ToString());
}
uj5u.com熱心網友回復:
我得到了解決方案。謝謝@Cleptus
我的代碼中的 SendEmail() 方法有
SmtpClient smC= new SmtpClient();
MailMessage mM= new MailMessage();
我在 finally 塊中添加了 SMTPClient 和 MailMessage 的處理
try
{
smC.Send(mM);
}
catch (Exception ex)
{
Err = ex.Message;
}
finally {
mM.Dispose();
smC.Dispose();
}
uj5u.com熱心網友回復:
您需要在“關閉”之后而不是之前洗掉檔案。只要 close 沒有執行,檔案就會在流回圈中,它算作自己的行程,因此在檔案關閉之前不能洗掉。希望這可以幫助。我猜你的 close 陳述句低于該代碼。將其移動到洗掉陳述句之前。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/393810.html
上一篇:C#檔案輸出列印超過1次
下一篇:如何洗掉一項Vectorsc
