How to configure custom event?

I need to create a custom event that should appear if a new / existing file was found / created in a specific directory. To check if a new file has been created, I use SystemFileWatcher, which works fine. To check if any files exist when the program starts, I wrote a few lines and this works.

I use this class for args events:

public class FileDetectEventArgs : EventArgs
{
    public String Source { get; set; }
    public String Destination { get; set; }
    public String FullName { get; set; }

    public FileDetectEventArgs(String source, String destination, String fullName)
    {
        this.Source = source;
        this.Destination = destination;
        this.FullName = fullName;
    }
}

If SystemFileWatcher raises an event created using FileCreated, I use the following lines of code:

public void onFileCreated(object sender, FileSystemEventArgs e)
{
    // check if file exist
    if (File.Exists(e.FullPath))
    {
        OnNewFileDetect(new FileDetectEventArgs(source, destination, e.FullPath));  
    }
}

And if the file exists, I try to raise the event like this:

public void checkExistingFiles(String source, String filter)
    {
        DirectoryInfo di = new DirectoryInfo(source);
        FileInfo[] fileInfos = di.GetFiles();
        String fileFilter = filter.Substring(filter.LastIndexOf('.'));       

        foreach (FileInfo fi in fileInfos)
        {
            if (fi.Extension.Equals(fileFilter))
            {
                OnNewFileDetect(new FileDetectEventArgs(source, destination, fi.FullName));                   
            }
        }
    }

Here is the OnNewFileDetect-Event:

protected void OnNewFileDetect(FileDetectEventArgs e)
    {
        if (OnNewFileDetectEvent != null)
        {
            OnNewFileDetectEvent(this, e);
        }
    }

, onFileCreated-Event OnNewFileDetect-Event, . checkExistingFiles OnNewFileDetect-Event, . , OnNewFileDetectEvent null, . null, onFileCreated-Event ?

+3
2

null, onFileCreated-Event?

null, - .


, , #/.NET . :

// The event...
public EventHandler<FileDetectedEventArgs> NewFileDetected;

// Note the naming
protected void OnNewFileDetected(FileDetectedEventArgs e)
{
    // Note this pattern for thread safety...
    EventHandler<FileDetectedEventArgs> handler = this.NewFileDetected; 
    if (handler != null)
    {
        handler(this, e);
    }
}
+2

@ ; null, .

, :

if (OnNewFileDetectEvent != null)
{
    OnNewFileDetectEvent(this, e);
}

, , OnNewFileDetectEvent null if, . :

var del = OnNewFileDetectEvent;
if (del != null)
{
    del(this, e);
}

del null, if.

, . On, , .

+1

All Articles