Newbie Question

dreber

Member
Joined
Jul 15, 2003
Messages
6
I am wrtining my first c# app that will monitor a perticular file location to do things.

When I build the project I get :

An object reference is required for the nonstatic field, method, or property JobMonitor.StartUp.watcher at:

watcher.Star ch();


Here is the code:

using System;
using System.Windows.Forms;


namespace JobMonitor
{
/// <summary>
/// Summary description for Main.
/// </summary>
public class StartUp
{
FileWatch watcher = new FileWatch();
static void Main()
{
watcher.Star ch(); // <-- error at this point
Application.Run(new frmFortestingonly());
}


}
}


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;

namespace JobMonitor
{
/// <summary>
/// Summary description for FileWatch.
/// </summary>
public class FileWatch
{
FileSystemWatcher watcher = new FileSystemWatcher();
public FileWatch()
{
}

public void Star ch()
{


watcher.Path = "D:\\";

watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Attributes
| NotifyFilters.LastAccess | NotifyFilters.LastWrite |
NotifyFilters.Security | NotifyFilters.Size;


watcher.Changed += new FileSystemEventHandler(OnFileEvent);
watcher.Created += new FileSystemEventHandler(OnFileEvent);

watcher.EnableRaisingEvents = true;
}
//-----------------------------------------------------------------------
public void OnFileEvent(object source, FileSystemEventArgs fsea)
{
DateTime dt = new DateTime();
dt = System.DateTime.UtcNow;
MessageBox.Show("",dt.ToLocalTime() + " " + fsea.ChangeType.ToString() + " " + fsea.FullPath) ;

}
//----------------------------------------------------------------------
public void OnRenameEvent(Object source, RenamedEventArgs rea)
{
DateTime dt = new DateTime();
dt = System.DateTime.UtcNow;
MessageBox.Show("",dt.ToLocalTime() + " " + rea.ChangeType.ToString() + rea.OldFullPath+ " to " +" " + rea.FullPath);
}
//------------------------------------------------------------------

}
}


Any help would be great.

Thanks
 
I am not sure what is happing. I have a function named (each letter is spelled out) "S t a r t W a t c h()" but the newsgroup is displaying Star ch().
 
watcher is an instance member of your StartUp class. However, you are trying to reference it from Main(), which is a static method. Since a static method does not have an implicit this reference, you cannot reference instance members, only static members.

You have three choices:

1. Declare and initialize watcher inside your Main() method, instead of making it a member.

2. Make watcher a static member of your StartUp class (just declare it "static FileWatch watcher").

3. Create an instance of class StartUp and use that, as in "new StartUp().watcher.StartW
 


Write your reply...

Similar threads

P
Replies
0
Views
128
Priya Bange
P
A
Replies
0
Views
154
Afshan Gul
A
D
Replies
0
Views
163
dabina2018
D
Back
Top