-2

大家好,我正忙于编写一个小型控制台应用程序,该应用程序将接收文本文件并邮寄它们,但邮寄后必须将邮寄的文本文件移动到备份文件夹文件中......问题是当我尝试删除文件时出现此错误,但我知道我没有使用该文件。

该进程无法访问文件“C:\Files\Configs\Errorlog.txt”,因为它正被另一个进程使用。

我使用了两种方法 file.move 和 file.copy 然后尝试删除它仍然不起作用我得到同样的错误请协助

class Program
{
    static void Main(string[] args)
    {
        {
            MailMessage mail = new MailMessage();

            SmtpClient SmtpServer = new SmtpClient("******");
            mail.From = new MailAddress("*********");
            mail.To.Add(ConfigurationSettings.AppSettings["EmailReceiver"]);
            mail.Subject = "Test HHjhihH- Mail";
            mail.Body = "TestMail";

            string folder = ConfigurationSettings.AppSettings["ConfigPath"];

            try
            {
                string[] txtfiles = Directory.GetFiles(folder, "*.txt");

                foreach (var txtfile in txtfiles)  //FileInfo file in Files )
                {
                    if (!File.Exists("ConfigPath"))//txtfile.Length != 0)
                    {
                        mail.Attachments.Add(new System.Net.Mail.Attachment(txtfile));

                        Console.WriteLine("sending Config File....");
                    }
                    else
                    {
                        Console.WriteLine("No files in the directory");

                        return;
                    }
                }

            }
            catch (Exception)
            {
                Console.WriteLine("Incorrect Path" + ConfigurationSettings.AppSettings["ConfigPath"] + ",does not exist");
                return;
            }

            SmtpServer.Port = ****;
            SmtpServer.Send(mail);
            Console.WriteLine("Message Sent");

        }

        {



            string fileName = string.Empty;
            fileName = "Errorlog.txt";
            string sourceFile = @"C:\Files\Configs\" + fileName;
            string destinationFile = @"C:\Files\BackupConfigs\" + fileName;

            // To move a file or folder to a new location:

            **//error PROBLEM OCCRURS HERE**

            File.Copy(sourceFile, destinationFile);
       // copies the file but wont delete original file

            File.Delete(@"C:\Files\Configs\Errorlog.txt");

        // when i use File.move(sourceFile, destinationFile); i get same error


        }}
4

4 回答 4

2

您需要将结果分配给new System.Net.Mail.Attachment(txtfile)变量。

var attachment = new System.Net.Mail.Attachment(txtfile);

发送邮件后,您必须处理附件:

attachment.Dispose();

它保持文件打开。

于 2013-10-09T10:17:20.750 回答
0

我想Directory.GetFiles(folder, "*.txt")提供纯文件名。因此,要么采用绝对文件名,要么确保文件位于执行目录中(调试、发布等)

于 2013-10-09T10:16:24.950 回答
0

我认为每次尝试使用文件访问时都必须使用 using 子句。如果您不这样做,则在您运行应用程序一次后,该文件将在后台使用!

于 2013-10-09T10:24:39.563 回答
0
        SmtpServer.Port = ****;
        SmtpServer.Send(mail); 
        Mail.Dispose();
        Console.WriteLine("Message Sent");

发送邮件后,我使用 Mail.dispose() 它解决了问题,然后我可以在发送后删除文件。感谢您的投入

于 2013-10-09T11:11:31.333 回答