0

Ive a folder monitoring application where around 25 filewatchers monitoring 25 folders. Each of the filewatchers named fsw1,fsw2 ....

bCreateFileCheck = True
fsw1 = New FileSystemWatcher(My.Settings.UserRootFolder1)
fsw1.IncludeSubdirectories = True
fsw1.EnableRaisingEvents = True
fsw1.NotifyFilter = (NotifyFilters.LastAccess Or NotifyFilters.LastWrite Or NotifyFilters.FileName)

So this is repeating for the 25 folders, but only difference is name changing of fsw1 to fsw2,fsw3 etc. and also My.Settings.UserRootFolder1 to My.Settings.UserRootFolder2,My.Settings.UserRootFolder3 etc.

So how can we achieve this using for loop without writing individual code blocks for every filewatchers. I guess using some reflection techniques it can be achieved.

1 Answer 1

2

Don't make your life harder than it needed to be. Use an array (or List(Of T) if you need something flexible):

Dim watchers(24) As FileSystemWatcher
For i As Integer = 0 To watchers.GetUpperBound(0)
    Dim path = CStr(My.Settings.Item("UserRootFolder" & (i + 1)))
    watchers(i) = New FileSystemWatcher(path)
    'Do further initialization...       
Next

If the structure is fixed and you cannot really change it, you can set the variables to the objects that you created in the For loop. So change the loop as follows:

'...
Dim watcher = New FileSystemWatcher(...)
Me.GetType().GetField("fsw" & (i + 1)).SetValue(Me, watcher)

This gets the field with the appropriate name and sets its value to the object that you just created (I assume that it is a field based on its naming).

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry friend, actually its an existing code on the project been runnning for 3 4 years i guess. So there is lots of places where its using. So any possibility with that way other than array?
Then I would strongly recommend refactoring the code. If that is not an option, I have added some more information to my answer.
Thats really nice my friend.. Thanks for that.. Made my day

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.