更新时间:2023-01-29 19:51:05
已有机制到位为此,称为 FileSystemWatcher Class [ ^ ]。
点击链接查看示例。
而不是试图轮询日期我建议你改用FileSystemWatcher并处理Changed事件。请查看此参考,其中包含一个示例: https://msdn.microsoft.com/en-us/ library / system.io.filesystemwatcher [ ^ ]
Hey everyone,
I have one folder which has one csv file. I want to read this file when it is modified or update, I want to create loop that it waits for file update and when file update i.e. its date modified changes , quickly read that file. and again wait.
Is that possible?
I written following code but it does not work proper. Correct me.Thank you.
private void button1_Click(object sender, EventArgs e)
{
for (int p = 0; p >= 0; p++)
{
DateTime dt = File.GetLastWriteTime(filepath);
DateTime date = File.GetCreationTime(filepath);
if (File.Exists(filepath))
{
if (date != dt)
{
task();
}
}
}
}
public void task()
{
using (FileStream fs = new FileStream(filepath,FileMode.Open,FileAccess.Read))
{
using (StreamReader sr = new StreamReader(fs))
{
string[] line = sr.ReadLine().Split(',');
textBox1.Text = "File update"+ Environment.NewLine;
}
}
}
There is already a mechanism in place for this, called the FileSystemWatcher Class[^].
Follow the link and have a look at the examples.
Instead of attempting to poll the date I suggest you use a FileSystemWatcher instead and handle the "Changed" event. Check this reference which includes an example: https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher[^]