关闭文件后删除.xlsx或.pdf [英] Delete .xlsx or .pdf after closing file

查看:117
本文介绍了关闭文件后删除.xlsx或.pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试在使用它们后删除.xlsx或.pdf文件.创建文件时,我会显示它们,但是用户希望在关闭文件后自动删除文件.

I'm trying to delete .xlsx or .pdf files after using them. When files are created I display them, but then users want automatic file deletion after closing them.

我尝试了几件事,但似乎都无法正常工作.问题:

I've tried couple of things, but none of them seem to work properly. Issue:

当打开多个文件(.xlsx或.pdf)时,我无法终止单个进程,就像一个文件一样.取而代之的是,仅当我关闭所有相同的过程(Excel或PDF文件)时,该文件才会被删除.在我调查这种情况时,是因为Excel或PDF仅作为一个实例工作.但是,当我只打开一个文件时,代码可以按预期工作...

When opened multiple files (.xlsx or .pdf) I can't terminate a single process, like just a single file. Instead what happens is that file get's deleted only when I close all same processes (Excel or PDF files). As I investigated this happens because Excel or PDF works as one instance only. However code works as expected when I have only one file opened...

这是我到目前为止所拥有的:

This is what I have so far:

 var process= Process.Start(file_path); //file_path is global variable
 Set_event(process);

 private void Set_event(Process process)
 {
        process.EnableRaisingEvents = true;
        process.Exited += new EventHandler(Delete_File);
 }

 public void Delete_File(object sender, EventArgs e)
 {
        //Delete file on close
        File.Delete(file_path);
 }

我也尝试过使用 FileOptions DeleteOnClose 方法,但是很遗憾,该方法不会向用户显示文件,并且在使用它们后并不会立即删除文件,仅在我的获胜应用程序关闭后.这不是我想要的输出,但是至少删除了文件,所以如果我能解决的话,我也会部分满意.这是我的那句话:

I've also tried with DeleteOnClose method of FileOptions, but unfortunally that doesn't display file to user and doesn't quite delete file immediately after using them, only after my win app is closed. That isn't my desired output, but at least files are deleted, so If I could fix that I would be partially satisfied too. Here is my line for that:

   var open_file = new FileStream(file_path,FileMode.Open, FileAccess.ReadWrite,FileShare.ReadWrite, 512, FileOptions.DeleteOnClose);

话虽如此,我还有其他选择吗?预先感谢您的帮助.

With all that said, are there any other options I missed ? Thanks for help in advance.

推荐答案

我已经尝试了几乎所有可以找到的东西(Processed Exited_Event的各种变体,使用FileSystemWatcher进行监视,使用DeleteOnClose-甚至API创建文件),但是没有他们按预期工作.

I've tried almost everything I could find (different variations of Exited_Event for Process, monitoring with FileSystemWatcher, creating files with DeleteOnClose - even API), but none of them worked as expected.

一切都以我首先描述的问题结束或失败-某些应用程序(例如Microsoft Excel或Adobe Acrobat)使用一个实例来打开文件(.pdf或.xls/.xlsx),因此您不能仅引用打开更多文件时,将单个文件作为对象.这意味着您要么在尝试将Exited_event分配给单个文件时遇到错误,要么没有错误,但是仅当您关闭所有相同类型的文件时,文件才被删除...

Everything ends or fails with issue I described in first place - some apps, like Microsoft Excel or Adobe Acrobat uses one instance to open a file (.pdf or .xls/.xlsx), so you can't just reference a single file as object while you have opened more files. That means you either end up with an error when trying to assign Exited_event to single file, or no error but file gets deleted only when you close all files with same type...

足够幸运我弄清楚了一件事:何时您打开了多个问题文件(.pdf或.xlsx),这在操作系统的后台发生了:如果您当时遍历相同类型的进程,则将获得正在使用的特定实例的列表.

BUT fortunate enough I figured out one thing: WHEN you have opened more than one file in question (.pdf or .xlsx) something happens in background of OS: If you loop through processes of same type at that time, you'll get a list of particular instance that is in use.

换句话说,当您打开2个Excel文件时,循环遍历"过程仅向您显示"EXCEL"过程当前处于活动状态的文件.

In other words, while you have 2 Excel files opened, loop through processes is showing you only a file which is currently active for "EXCEL" process.

因此,这使我找到了一种可以解决此问题的全新方法.为了对此有一个完整的解决方案,您必须:

So, that leaded me to a completely new approach that might solve this issue. In order to have a complete solution for this you have to:

1..创建一种方法来检查文件是否不再使用.

1. Create a method to check whether file is no longer in use.

2..将计时器设置为2秒的延迟,以确保过程真正结束.也许应该出于不同目的将其增加...

2. Set a Timer with a delay of 2 seconds, to make sure process really ends. Maybe this should be incremented for different purposes...

3..设置一个Timer_tick事件,在该事件中循环处理以查看特定文件是否被列为活动文件,以及用户是否已关闭该文件.正如其他用户所描述的那样,该方法不太准确,但是由于设置了Timer的延迟,我认为应该不再有任何问题了.

3. Set a Timer_tick event, where you loop processes to see whether particular file is listed as active, and If user has already closed this file. As described by other users this method isn't quite accurate, but with setting delay for Timer I think there shouldn't be any problems anymore.

这是完整的代码(对于.pdf和.xlsx-这正是我所需要的):

Here is a complete code for this (for .pdf and .xlsx - that is what I needed):

   //as global variable
   System.Windows.Forms.Timer delete_file = new System.Windows.Forms.Timer(); 

    Process.Start(file_path); //file_path is global variable

    delete_file.Tick += new EventHandler(timer_Tick); 
    delete_file.Interval = (2000);              
    delete_file.Enabled = true;                     
    delete_file.Start();

    private void timer_Tick(object sender, EventArgs e)
    {
        Boolean file_is_opened = false;

        // Loop processes and list active files in use
        foreach (var process in Process.GetProcesses())
        {
          if (process.MainWindowTitle.Contains(Path.GetFileName(file_path)))
          {
             file_is_opened = true;
          }
        }

         //If our file is not listed under active processes we check 
         //whether user has already closed file - If so, we finally delete It
         if (file_is_opened==false)
         {
            if (!File_In_Use(new FileInfo(file_path)))
            {
                 File.Delete(file_path);
                 delete_file.Enabled = false;
                 delete_file.Stop();
                 return;
             }
          }
     }

     private bool File_In_Use(FileInfo file)
     {
         //Method to check whether file is in use

         FileStream stream = null;

         try
         {
              //If file doesn't exist
              if (!file.Exists)
              {
                     return false;
              }

              stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
         }
         catch (IOException)
         {
               //File is unavailable:
              //because someone writes to It, or It's being processed
              return true;
         }
         finally
         {
            if (stream!=null)
            {
              stream.Close();
            }
         }

             //File not locked
             return false;
      }

这就是我的做法.它可能不是一个完美的解决方案,但对我来说,在Win 10上仍然可以正常使用.

This is how I did It. It might not be a perfect solution, but that works for me on Win 10 with no errors so far.

如果有人建议修复较高的代码,请告诉我.否则,我希望这会对以后的人有所帮助,因为我注意到过去已经对此有一些疑问,没有适当的答案.

If someone has a suggestion to fix upper code, please let me know. Otherwise I hope this will help someone in future as I noticed there were already some questions about this in past, with no proper answer.

这篇关于关闭文件后删除.xlsx或.pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆