FileSystemWatcher在文件保存之前启动-您如何“暂停"操作,这个过程? [英] FileSystemWatcher fires before file is saved - how do you "pause" the process?

查看:60
本文介绍了FileSystemWatcher在文件保存之前启动-您如何“暂停"操作,这个过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我尝试编码的逻辑:

Here is the logic I'm trying code:

Service监视目录中的.pptx文件. 如果文件已更改,请转换为jpg.然后执行其他任务,这些任务将在以后添加.

Service monitors a .pptx file in directory. If the file has changed perform convertion to jpg. Then do other tasks, which will be added later.

我正在使用文件wather对象,但是一旦打开文件即会触发,因此我想通过检查文件是否锁定"来停止该过程.我以为锁定时"循环可以解决问题,但是没有.下面是简化的代码原型,如果您能看一下它,我想建议我做错了什么,和/或是否有更好的方法为生产环境编写此代码. pptx文件可以打开很长时间.

I'm using file wather object but that fires as soon as I open the file, so I thought to stop the process by checking if the file is "locked". I thought a "while locked" loop would do the trick - but no. Below is reduced code prototype and I woiuld like to if you could look at it suggest what I'm doing wrong and/or if there is a better way to write this for a production environment. The pptx file can be open for a long time.

namespace FileWatcherDemo
{
   public class Program
   {

    static void Main(string[] args)
    {
        FileSystemWatcher fsWatcher = new FileSystemWatcher();
        fsWatcher.Path = @"e:\\";

        fsWatcher.NotifyFilter = NotifyFilters.LastWrite; 

        fsWatcher.Filter = "*.pptx";
        fsWatcher.Changed += new FileSystemEventHandler(fsWatcher_Changed);
        //fsWatcher.Created += new FileSystemEventHandler(fsWatcher_Changed);
        //fsWatcher.Deleted += new FileSystemEventHandler(fsWatcher_Changed);
        //fsWatcher.Renamed += new RenamedEventHandler(fsWatcher_Changed);
        fsWatcher.EnableRaisingEvents = true;
        Console.ReadKey();
    }        

    static void fsWatcher_Changed(object sender, FileSystemEventArgs e)
    {
        try
        {
            while( !IsFileLocked())
            {
                Console.WriteLine("Changed Event Fired");
                Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.Application();
                Presentation pptPresentation = app.Presentations.Open(@"e:\\HowTo.pptx", MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);

                pptPresentation.SaveAs(@"e:\\Output", PpSaveAsFileType.ppSaveAsJPG, MsoTriState.msoFalse);
                pptPresentation.Close();
            }
        }
        catch (Exception ex)
        {
            using (StreamWriter w = File.AppendText(@"e:\\ErrorLog.txt"))
            {
                Log(ex.Message.ToString(), w);
                Log(ex.StackTrace.ToString(), w);

                w.Close();
            }
        }

        Console.ReadKey();
    }

    static bool IsFileLocked()
    {
        FileStream fs = null;
        FileInfo file = new FileInfo(@"e:\\HowTo.pptx");            

        try
        {
            fs = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            return true;
        }
        finally
        {
            if(fs != null)
                fs.Close();
        }
        return false;
    }

    public static void Log(string LogMessage, TextWriter w)
    {
        w.Write("\r\nLog Entry: ");
        w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
        w.WriteLine("  :");
        w.WriteLine("  {0}", LogMessage.ToString());
        w.WriteLine("------------------------------------------");

        w.Flush();
    }
}

}

推荐答案

这是另一个想法:当FileSystemWatcher检测到更改(您说它立即触发文件打开)时,记录文件的LastModifiedTime并保持循环直到文件的LastModifiedTime发生更改(假设LastModifiedTime仅在文件保存时写入-我不知道何时完成),然后执行转换为JPG的过程.

Here's one other idea: When the FileSystemWatcher detects the change (You say it fires immediately the file is opened) record the LastModifiedTime of the file and keep looping until the LastModifiedTime of the file changes (Assuming the LastModifiedTime gets written only when the file is saved - I don't know when this is actually done) and then perform your process of converting to JPG.

编辑

添加应该演示如何跟踪文件修改时间的代码:

Adding code that should demonstrate how to track when a file has been modified:

class Program
{
    static void Main(string[] args)
    {
        Thread t = new Thread(()=> DoTest());
        t.Start();

        Console.WriteLine("Waiting...");
        Console.ReadKey();
    }

    private static void DoTest()
    {
        FileSystemWatcher fsw = new FileSystemWatcher("C:\\");
        fsw.Filter = "*.txt";
        fsw.Changed += new FileSystemEventHandler(fsw_Changed);
        fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);
        fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
        fsw.Created += new FileSystemEventHandler(fsw_Created);
        fsw.EnableRaisingEvents = true;
    }

    static void fsw_Created(object sender, FileSystemEventArgs e)
    {
        FileInfo fi = new FileInfo(e.FullPath);
        Console.WriteLine("File Created: "+e.FullPath);
        Console.WriteLine("Creation Time: " + fi.CreationTime.ToLongTimeString());
        Console.WriteLine("Last Access Time: " + fi.LastAccessTime.ToLongTimeString());
        Console.WriteLine("Last Write Time: " + fi.LastWriteTime.ToLongTimeString());
        Console.WriteLine("Length: " + fi.Length);

    }

    static void fsw_Renamed(object sender, RenamedEventArgs e)
    {
        FileInfo fi = new FileInfo(e.FullPath);
        Console.WriteLine("File Renamed: "+e.FullPath);
        Console.WriteLine("Creation Time: " + fi.CreationTime.ToLongTimeString());
        Console.WriteLine("Access Time: " + fi.LastAccessTime.ToLongTimeString());
        Console.WriteLine("Last Write Time: " + fi.LastWriteTime.ToLongTimeString());
        Console.WriteLine("Length: " + fi.Length);
    }

    static void fsw_Deleted(object sender, FileSystemEventArgs e)
    {
        FileInfo fi = new FileInfo(e.FullPath);
        Console.WriteLine("File Deleted: "+e.FullPath);
        Console.WriteLine("Creation Time: " + fi.CreationTime.ToLongTimeString());
        Console.WriteLine("Last Access Time: " + fi.LastAccessTime.ToLongTimeString());
        Console.WriteLine("Last Write Time: " + fi.LastWriteTime.ToLongTimeString());

    }

    static void fsw_Changed(object sender, FileSystemEventArgs e)
    {
        FileInfo fi = new FileInfo(e.FullPath);
        Console.WriteLine("File Changed: "+e.FullPath);
        Console.WriteLine("Creation Time: " + fi.CreationTime.ToLongTimeString());
        Console.WriteLine("Last Access Time: " + fi.LastAccessTime.ToLongTimeString());
        Console.WriteLine("Last Write Time: " + fi.LastWriteTime.ToLongTimeString());
        Console.WriteLine("Length: " + fi.Length);
    }
}

这篇关于FileSystemWatcher在文件保存之前启动-您如何“暂停"操作,这个过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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