Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

C#
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;
        }
    }
}
Posted
Comments
Philippe Mori 5-Nov-15 13:19pm    
Never, never write code like that. It will waste lot of CPU time.

There is already a mechanism in place for this, called the FileSystemWatcher Class[^].

Follow the link and have a look at the examples.
 
Share this answer
 
Comments
Member 11543226 5-Nov-15 6:38am    
Thanks works.
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[^]
 
Share this answer
 
Comments
Member 11543226 5-Nov-15 6:38am    
Thanks works.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900