0

こんにちは、私のコードには 2 つの部分があります。1 つは、Excel を作成してからメールで送信することです。次のようなエラーが表示されます: IOException: The process cannot access the file 'filename' because it is being used by another process

どうすればこれを回避できますか: コードは次のとおりです:

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

1 に答える 1

0

私は常に次のように Excel-Interop-Component を終了します。

owB.Close();
owX.Quit();
Marshal.FinalReleaseComObject(oSheet);
Marshal.FinalReleaseComObject(owB);
Marshal.FinalReleaseComObject(owX);

しかし、あなたの問題は、IOException管理者権限なしではディレクトリ C:\ にアクセスできないことです。

代わりにユーザーパスに保存してみてください(または管理者権限でプログラムを起動してください):

string loc = @"C:\Users\MYUSER\Desktop";

または次を使用して:

string loc = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

ここに画像の説明を入力

于 2013-06-04T15:18:09.207 に答える