When one or more files are added to a folder "SentBox", my app will detect it and proceed them ONE BY ONE, here is my code:
public void SetUp_Timers()
{
MsgHandler.Interval = new TimeSpan(0, 0, 1);
MsgHandler.Tick += MsgHandler_Tick;
MsgHandler.Start();
}
private void MsgHandler_Tick(object sender, EventArgs e)
{
if (Directory.GetFiles(Path_SentBox).Count() > 0)
{
string pt = Directory.GetFiles(Path_SentBox)[0];
Message ms = JsonConvert.DeserializeObject<Message>(Security_ReadAllText(pt));
ProceedMsg(ms, pt);
}
}
public async void ProceedMsg(Message msg, string msgpath)
{
MsgHandler.Stop();
//more code....
File.Delete(msgpath);
MsgHandler.Start();
}
So far, this never gives me an unexpected result.
Recently, I found a class called FileSystemWatcher
. Based on what they say here and here, the class is used to watch for changes in a specified directory.
My questions:
- Is it possible to achieve my goal with
FileSystemWatcher
? - If so, which one is better?
- And, is there a better way than these two?
EDIT:
I'm not sure if you need this:
public void SendMessage(Message msg)
{
string fn = msg.Type + "_" + FileNameFix(DateTime.Now.ToShortDateString() + DateTime.Now.ToLongTimeString() + Path.GetRandomFileName().Replace(".", "") + ".kmsg");
Security_WriteAllText(Path_SentBox + "\\" + fn, JsonConvert.SerializeObject(msg));
}