Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 136,533 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,800 people online right now. Registration is fast and FREE... Join Now!




how can I stop after finding the file?

 
Reply to this topicStart new topic

how can I stop after finding the file?

skyHigh
22 Aug, 2008 - 02:23 PM
Post #1

D.I.C Head
**

Joined: 1 Oct, 2007
Posts: 87


My Contributions
Hello Everyone,

From the simple code below, how can I stop the Timer when the file is found? And how come my textBox inside the TimeEvent doesn't display? That txtBox I create under design view and given it a name as textBox. I try to disable the Timer, but it doesn't disable.

For what I really want is to stop the Timer after the file is found. Basically it will keep checkiing if the file has existed yet, if not then keep checking until the file exists. Although I'm not sure if that is an appropriate way to search for existing file.
CODE

    public partial class Form1 : Form
    {
        public delegate void stopTime(object sender, stopTimeEventArg e);

        private string textFile = "exitFile.txt";
        private int count = 0;
        private System.Timers.Timer time;
        private bool fileFound = false;

        public Form1()
        {
            InitializeComponent();
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.AppendText("searching for file...");
            time = new System.Timers.Timer();
            time.Enabled = true;
            time.Elapsed += new ElapsedEventHandler(TimerEvent);
            time.Interval = 2000;//every two seconds will raise an event.
        }

        private void TimerEvent(object source, ElapsedEventArgs e)
        {
            count++;
            if(File.Exists(textFile))
            {

                    txtBox.AppendText("File found! " + count + " " + textFile);
                    time.Enabled = false;
            }

            txtBox.AppendText("File not found! " + count + " " + textFile);
        }



Thanks,

This post has been edited by skyHigh: 22 Aug, 2008 - 02:27 PM
User is offlineProfile CardPM
+Quote Post

jacobjordan
RE: How Can I Stop After Finding The File?
22 Aug, 2008 - 04:03 PM
Post #2

class Me : Perfection
Group Icon

Joined: 11 Jun, 2008
Posts: 1,166



Thanked: 32 times
Dream Kudos: 1625
My Contributions
Did you get a Cross-thread operation not valid exception? I replicated your code, and it gave me an error under the TimerEvent function when i tried to access txtBox. If that is the case, changing the System.Timers.Timer object you are using to a System.Windows.Forms.Timer object should solve the problem. Basically, change your code to look like this
csharp

public delegate void stopTime(object sender, stopTimeEventArg e);

private string textFile = "exitFile.txt";
private int count = 0;
private System.Windows.Forms.Timer time;
private bool fileFound = false;

private void button1_Click(object sender, EventArgs e)
{
textBox1.AppendText("searching for file...");
time = new System.Windows.Forms.Timer();
time.Enabled = true;
time.Tick += new EventHandler(time_Tick);
time.Interval = 2000;//every two seconds will raise an event.
}

void time_Tick(object sender, EventArgs e)
{
count++;
if (File.Exists(textFile))
{

txtBox.AppendText("File found! " + count + " " + textFile);
time.Enabled = false;
}

txtBox.AppendText("File not found! " + count + " " + textFile);
}

User is online!Profile CardPM
+Quote Post

skyHigh
RE: How Can I Stop After Finding The File?
22 Aug, 2008 - 04:48 PM
Post #3

D.I.C Head
**

Joined: 1 Oct, 2007
Posts: 87


My Contributions
Recently I often get the Cross-thread operation, and I didn't know that Timer defined in system as well as windowform, however I don't have get any crossing thread operation based on my code above..

what is stopTimeEventArg? I use it and it gives me error. Mentioning I'm missing reference or namespace.
User is offlineProfile CardPM
+Quote Post

Jayman
RE: How Can I Stop After Finding The File?
22 Aug, 2008 - 05:58 PM
Post #4

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 6,947



Thanked: 42 times
Dream Kudos: 500
Expert In: C#, VB.NET, Java

My Contributions
Use Timer.Start() to start the timer and Timer.Stop() to stop it. Setting the Enabled property only determines whether you can use the timer.
User is offlineProfile CardPM
+Quote Post

jacobjordan
RE: How Can I Stop After Finding The File?
22 Aug, 2008 - 06:42 PM
Post #5

class Me : Perfection
Group Icon

Joined: 11 Jun, 2008
Posts: 1,166



Thanked: 32 times
Dream Kudos: 1625
My Contributions
QUOTE(jayman9 @ 22 Aug, 2008 - 08:58 PM) *

Use Timer.Start() to start the timer and Timer.Stop() to stop it. Setting the Enabled property only determines whether you can use the timer.

I'm sorry, but in my experience, they've both worked fine.

QUOTE(skyHigh @ 22 Aug, 2008 - 07:48 PM) *

Recently I often get the Cross-thread operation, and I didn't know that Timer defined in system as well as windowform, however I don't have get any crossing thread operation based on my code above..

what is stopTimeEventArg? I use it and it gives me error. Mentioning I'm missing reference or namespace.

I have no idea what the stopTimerEventArg is. I too, had to delete that line entirely to make my application run when i tested it. I assumed it was something you were using for an unrelated task, so that's why i kept it in there. As far as i know, deleting that line entirely will resolve your error.
User is online!Profile CardPM
+Quote Post

Jayman
RE: How Can I Stop After Finding The File?
22 Aug, 2008 - 07:21 PM
Post #6

Student of Life
Group Icon

Joined: 26 Dec, 2005
Posts: 6,947



Thanked: 42 times
Dream Kudos: 500
Expert In: C#, VB.NET, Java

My Contributions
While it is true that the Enabled property will start and stop the timer, so I stand corrected, the Start and Stop method were designed for this purpose.

User is offlineProfile CardPM
+Quote Post

jacobjordan
RE: How Can I Stop After Finding The File?
22 Aug, 2008 - 08:12 PM
Post #7

class Me : Perfection
Group Icon

Joined: 11 Jun, 2008
Posts: 1,166



Thanked: 32 times
Dream Kudos: 1625
My Contributions
The actual code for the System.Windows.Forms.Timer.Start() event
csharp

/// <summary>Starts the timer.</summary>
/// <filterpriority>1</filterpriority>
/// <PermissionSet><IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence" /><IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true" /></PermissionSet>
public void Start()
{
this.Enabled = true;
}

Same with the stop event, just switched up. Just saying. smile.gif
User is online!Profile CardPM
+Quote Post

skyHigh
RE: How Can I Stop After Finding The File?
24 Aug, 2008 - 11:42 AM
Post #8

D.I.C Head
**

Joined: 1 Oct, 2007
Posts: 87


My Contributions
Thanks everyone for the replies. I tried to replace using Start() and Stop(), but still doesn't wait.

Here are the steps that I execute the program. Before I execute the program, I navigate to the currrent project folder to make sure there is no text file in there yet then I execute the program. After thrree or four seconds later I copy the text file and paste onto the currrent project folder and the messageBox says it found file, but it just doesn't stop.

CODE

        private System.Windows.Forms.Timer WindowFormTime;

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.AppendText("searching for file...");

            //Now usiing System.Timer.
            //time = new System.Timers.Timer();
            //time.Start();
            //time.Elapsed += new ElapsedEventHandler(TimerEvent);
            //time.Interval = 2000;//every two seconds will raise an event.

            //Using Windows.Forms Timer.
            WindowFormTime = new System.Windows.Forms.Timer();
            WindowFormTime.Enabled = true;
            WindowFormTime.Tick += new EventHandler(time_Tick);
            WindowFormTime.Interval = 2000;          

        }

        //An Event for Using Windows.Forms Timer
        void time_Tick(object sender, EventArgs e)
        {
            count++;
            if (File.Exists(textFile))
            {

                MessageBox.Show("File found! " + count + " " + textFile);
                WindowFormTime.Enabled = false;
                WindowFormTime.Stop();
            }

            MessageBox.Show("File Not found! " + count + " " + textFile);
        }




This post has been edited by skyHigh: 24 Aug, 2008 - 12:14 PM
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: How Can I Stop After Finding The File?
24 Aug, 2008 - 12:23 PM
Post #9

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 8,996



Thanked: 125 times
Dream Kudos: 8625
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
For starters, you cannot alter a GUI element, in this case a TextBox, from outside the thread that created the element, which is the main thread the application runs in, except through a delegate. That's why you're getting the cross-thread exception. Here's a tutorial on Cross Thread Communication that discusses marshaling the call on to the main application's thread. It's written in C# but the same logic applies to all .Net languages.
User is online!Profile CardPM
+Quote Post

skyHigh
RE: How Can I Stop After Finding The File?
24 Aug, 2008 - 12:34 PM
Post #10

D.I.C Head
**

Joined: 1 Oct, 2007
Posts: 87


My Contributions
QUOTE(PsychoCoder @ 24 Aug, 2008 - 01:23 PM) *

For starters, you cannot alter a GUI element, in this case a TextBox, from outside the thread that created the element, which is the main thread the application runs in, except through a delegate. That's why you're getting the cross-thread exception. Here's a tutorial on Cross Thread Communication that discusses marshaling the call on to the main application's thread. It's written in C# but the same logic applies to all .Net languages.



That's strange because it doesn't complain about threading crossing error. It prints out the text phrase onto the textbox.
User is offlineProfile CardPM
+Quote Post

skyHigh
RE: How Can I Stop After Finding The File?
24 Aug, 2008 - 02:51 PM
Post #11

D.I.C Head
**

Joined: 1 Oct, 2007
Posts: 87


My Contributions
Can anyone please explain why this works because I just fix the code, but I don't understand why.

Based on the code above, I just switch the MessageBox.Show() coming after I set the timer enabled to False then it works. Now The message box no longer executed otherwise the message box displays over and over.

CODE

        //An Event for Using Windows.Forms Timer
        void time_Tick(object sender, EventArgs e)
        {
            count++;
            if (File.Exists(textFile))
            {
                WindowFormTime.Enabled = false;
                MessageBox.Show("File found! " + count + " " + textFile);

                WindowFormTime.Stop();
            }

            MessageBox.Show("File Not found! " + count + " " + textFile);
        }


This post has been edited by skyHigh: 24 Aug, 2008 - 03:01 PM
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/2/08 10:10PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month