這裏是我試圖編碼的邏輯:FileSystemWatcher在保存文件之前觸發 - 您如何「暫停」該過程?
服務監視目錄中的.pptx文件。 如果文件已經更改,請執行轉換爲jpg。然後執行其他任務,這些任務將在稍後添加。
我正在使用文件捕捉對象,但一旦我打開文件就會觸發,所以我想通過檢查文件是否「鎖定」來停止進程。我以爲一個「鎖定」循環會做的伎倆 - 但沒有。下面是簡化的代碼原型,如果你能看看它,我就想知道我做錯了什麼和/或是否有更好的方法來爲生產環境編寫代碼。 pptx文件可以打開很長時間。
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();
}
}
}
是,FileInfo中LastAccesTime dislplays的確他們時間,這不是當前的時間,這就是我想要的。然而,沒有一個屬性可以跟蹤變化。你如何測試?謝謝。 – Risho
@裏索我不知道你爲什麼說沒有財產跟蹤變化。我正在用示例代碼編輯我的答案。我能夠監視文件上的更改事件,並且每次修改文件時,DID的確會增加。 – Icarus
becase的所有fsw_方法火的,當我點擊時不將文件保存的文件。我必須說明文件可能會打開幾個小時的事實。 – Risho