修改日期后如何读取文件? [英] How to read file when its date modified is change?

查看:80
本文介绍了修改日期后如何读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个文件夹,里面有一个csv文件。我想在修改或更新时读取此文件,我想创建等待文件更新的循环,当文件更新,即其修改日期更改时,快速读取该文件。再等一下。



这可能吗?



我写了下面的代码,但它不能正常工作。纠正我。谢谢。



 私人  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 = 文件更新 + Environment.NewLine;
}
}
}

解决方案

已有机制到位为此,称为 FileSystemWatcher Class [< a href =https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx\"target =_ blanktitle =New Window> ^ ]。



点击链接查看示例。


而不是试图轮询日期我建议你改用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[^]


这篇关于修改日期后如何读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆