Here is the logic I'm trying code:
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.
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();
}
}
}