您好我的代码中有两个部分,一个是创建一个Excel,然后通过电子邮件发送它。 我得到的错误是: IOException:进程无法访问文件'filename',因为它正被另一个进程
使用我怎样才能摆脱这种情况: 这是代码:
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();
}
}
答案 0 :(得分:0)
我总是以这种方式结束我的Excel-Interop-Component:
owB.Close();
owX.Quit();
Marshal.FinalReleaseComObject(oSheet);
Marshal.FinalReleaseComObject(owB);
Marshal.FinalReleaseComObject(owX);
但是IOException
的问题是你没有管理员权限就无法访问目录C:\。
请尝试将其保存在用户路径中(或start the program with admin permission):
string loc = @"C:\Users\MYUSER\Desktop";
或使用:
string loc = Environment.GetFolderPath(Environment.SpecialFolder.Personal);