Question

I am trying to write a project Windows Service in C#.

I wanna copy folder to another directory. I wrote the codes, everything is perfect

DirectoryInfo source = new DirectoryInfo("C:\\belgeler");
DirectoryInfo target = new DirectoryInfo("E:\\Backup");

This is correct implementation,but when i write this...

DirectoryInfo source = new DirectoryInfo(from_path);
DirectoryInfo target = new DirectoryInfo(to_path);

The error is 'A field initializer cannot reference the non-static field,method or property 'BACKUP(myproject_name).Service1.veri'

//string to_path = Registry.LocalMachine.GetValue("ToPath").ToString();  
//string from_path = Registry.LocalMachine.GetValue("FromPath").ToString();

This code block is working console application but in windows service it is not.

Was it helpful?

Solution

Your variables source and target are member variables of your class. The following code is allowed:

DirectoryInfo source = new DirectoryInfo("C:\\belgeler");
DirectoryInfo target = new DirectoryInfo("E:\\Backup");

It is permitted because it is not referencing any other member variables of your class. But when you try:

DirectoryInfo source = new DirectoryInfo(from_path);
DirectoryInfo target = new DirectoryInfo(to_path);

This references other variables from_path and to_path which is not permitted.

Move these variables to be local variables and that should solve your issue.

OTHER TIPS

You can set a field's value using another field as a parameter, you just need to do it in the constructor. This will ensure that the fields are set in the proper order.

A field initializer cannot reference the nonstatic field, method, or property

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top