嗨,我的代码中有两个部分,一个是创建一个 Excel,然后通过电子邮件发送它。我收到错误:IOException:该进程无法访问文件“文件名”,因为它正在被另一个进程使用
我怎样才能摆脱这个:这是代码:
public void createexcel()
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
oXL = new Excel.Application();
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
// oSheet = (Excel._Worksheet)oWB.ActiveSheet;
//oSheet = (Excel._Worksheet)oWB.Worksheets.get_Item(2);
//oSheet = (Excel._Worksheet)oWB.Worksheets.get_Item(2);
oSheet = (Excel._Worksheet)oWB.Worksheets.get_Item(1);
// oWB.Colors(1);
oSheet.Cells[1, 1] = "Expected_Result";
oSheet.Cells[1, 2] = "Actual_Result";
oSheet.Cells[1, 3] = "Test_Status";
//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "D1").Font.Bold = true;
oSheet.get_Range("A1", "D1").Font.Color = 0;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Excel.XlVAlign.xlVAlignCenter;
oSheet.Name = "Hotel_Total_Oppy_Verification";
loc = "c:\\" + "TestResults_" + DateTime.Now.ToString("ddMMMMyyHHMMss");
oWB.SaveAs(loc + ".xlsx");
oWB.Close();
}
public void emailtestresults (string testresult)
{
string to = "abc@abc.com";
string from = "abc@bc.com";
MailMessage message = new MailMessage(from, to);
message.Subject = " Test Result for Run of ." + DateTime.Today.ToString("DD/MM/YY/HHMMss") + "is " + emailresult;
message.Body = @"Verify the results from the attached excel sheet or look at the Screenshot.";
string PathToAttachment = loc + ".xlsx";
message.Attachments.Add(new Attachment(PathToAttachment));
SmtpClient client = new SmtpClient("xxxxxx");
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client.UseDefaultCredentials = true;
try
{
client.Send(message);
DateTime now = DateTime.Now;
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", ex.ToString());
Console.ReadLine();
}
}