我有一个文件,数据一直保存到... 我有一个计时器,每4秒运行一次 我的流程如下: 文件x.txt一直处于打开状态。 4秒后我想停止进程并通过电子邮件发送此文件。 我想一直重复上述步骤。
我的代码:
var timer = new System.Timers.Timer(4000);
timer.Enabled = true;
timer.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) =>
{
wrtiteToFile.Suspend();
SendEmail();
wrtiteToFile.Resume();
};
static void SendEmail()
{
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential =
new NetworkCredential("", "");
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("");
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Port = ;
smtpClient.Host = "";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
smtpClient.EnableSsl = true;
message.From = fromAddress;
message.Subject = "";
//Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "";
message.To.Add("");
message.Attachments.Add(new Attachment(Application.StartupPath + @"\log.txt"));
smtpClient.Send(message);
}
该进程无法访问该文件' C:\ log.txt'因为它正被另一个进程使用。 它不起作用。我能做到这一点的最佳方式是什么?我试过锁,但它也不起作用。 我必须使用.net framework 2.0
答案 0 :(得分:2)
您没有处置资源。这样就不确定何时释放资源(文件锁)。
您应该通过妥善处理资源来解决问题。 (免责声明,我没有检查过这个)
static void SendEmail()
{
using (SmtpClient smtpClient = new SmtpClient())
using (MailMessage message = new MailMessage())
using (Attachment attachment = new Attachment(Application.StartupPath + @"\log.txt"))
{
NetworkCredential basicCredential =
new NetworkCredential("", "");
MailAddress fromAddress = new MailAddress("");
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Port = "";
smtpClient.Host = "";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
smtpClient.EnableSsl = true;
message.From = fromAddress;
message.Subject = "";
//Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "";
message.To.Add("");
message.Attachments.Add(attachment);
smtpClient.Send(message);
}
}
using
语句将隐式调用一次性用法的Dispose
方法,从而释放文件句柄和其他类型的连接。
答案 1 :(得分:0)
您的SendMail方法块文件。最简单的方法修复:)
var timer = new System.Timers.Timer(4000);
timer.Enabled = true;
timer.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) =>
{
timer.Enabled = false;
wrtiteToFile.Suspend();
SendEmail();
wrtiteToFile.Resume();
timer.Enabled = true;
};