在编辑和发送文件和Thread.Sleep(1000)的while循环中出错

本文关键字:while 出错 1000 循环 Sleep 编辑 文件 Thread | 更新日期: 2023-09-27 18:13:56

我得到错误'IOException:进程无法访问文件文件路径,因为它正在被另一个进程使用',但我似乎无法理解为什么。我在我更大的项目中得到它,但我不希望这篇文章有一个巨大的代码块,所以我试图缩短它,所以请原谅愚蠢的类名和变量名。

using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Net.Mail;
using System.Threading;
namespace Test_Bench
{
    public class poo
    {
        public void penises()
        {
            StreamWriter chinatown;
            chinatown = new     StreamWriter("C:''Users''eggroll''Desktop''file.txt");
            chinatown.Write("SUP BOIS");
            chinatown.Close();
        }
    }
    public class hello
    {
        public void eggroll()
        {
            MailAddress senderAddress = new MailAddress("example@gmail.com");
            MailAddress receiverAddress = new MailAddress("example@gmail.com");
            MailMessage mail = new MailMessage(senderAddress, receiverAddress);
            System.Net.Mail.Attachment attachment;
            attachment = new     System.Net.Mail.Attachment("C:''Users''example''Desktop''file.txt");
            mail.Attachments.Add(attachment);
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.Credentials = new NetworkCredential(
                "example@gmail.com", "example");
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var chicken = new poo();
            var hello = new hello();
            while (true)
            {
                chicken.penises();
                hello.eggroll();
                Thread.Sleep(1000);
            }
        }
    }
}

在编辑和发送文件和Thread.Sleep(1000)的while循环中出错

您需要释放MailMessage,以便它关闭所有连接并释放它可能打开的任何资源句柄(例如,附件句柄):

public class hello
{
    public void eggroll()
    {
        MailAddress senderAddress = new MailAddress("example@gmail.com");
        MailAddress receiverAddress = new MailAddress("example@gmail.com");
        using (MailMessage mail = new MailMessage(senderAddress, receiverAddress))
        {
            System.Net.Mail.Attachment attachment;
            attachment = new     System.Net.Mail.Attachment("C:''Users''example''Desktop''file.txt");
            mail.Attachments.Add(attachment);
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.Credentials = new NetworkCredential(
                "example@gmail.com", "example");
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }
    }
}

这在发送邮件附件时尤为重要。