Here is the logic I'm trying to code:
The service controls the .pptx file in the directory. If the file has changed, convert to jpg. Then complete other tasks that will be added later.
I use the wather object file, but it fires as soon as I open the file, so I decided to stop the process by checking if the file is locked. I thought a "closed" loop would do the trick, but no. The following is a reduced prototype of the code, and I liked it if you could take a look at it, suggesting what I am doing wrong, and / or if there is a better way to write this for a production environment. The pptx file may 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(); } }
}
Risho source share