im trying to make something that can read a list off accounts from an online .txt file on my website but i keep getting the error
A field initializer cannot reference the non-static field, method, or property '*****.Form1.path'
im well and truly stumped as to how to fix the error, the code below is for locating and reading the online file but it refuses to work :(
string path = @"http://mywebsite.com/accounts.txt";
String[] saUsernames = File.ReadAllLines(path);
im well and truly confused -_-
To solve the compile-time issue, put the initialization in the constructor. You're simply not allowed to refer to one instance variable from the initializer of another. This is laid down in the C# specification in section 10.5.5.2:
A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple-name. In the example
class A { int x = 1; int y = x + 1; // Error, reference to instance member of this }
the variable initializer for
y
results in a compile-time error because it references a member of the instance being created.
It's unclear that you even need path
as an instance variable, to be honest:
public class Form1 : Form
{
private string[] userNames;
public Form1()
{
string path = "http://mywebsite.com/accounts.txt";
userNames = File.ReadAllLines(path);
}
}
Or if it's always going to read from that path anyway, you could just inline it:
public class Form1
{
private string[] userNames =
File.ReadAllLines("http://mywebsite.com/accounts.txt");
}
Not that either of these will actually work - File.ReadAllLines
takes a local filename - not a URL. You'll need WebClient
or something similar instead.
I strongly suggest you take a step back and work out what the logical state of the form is. Loading user names from a web site on construction feels like an odd thing for a form to do, to be honest. Additionally, you shouldn't perform potentially long-running operations (like fetching a web page) on the UI thread.
There's a lot to consider about your code - far more than the immediate compilation problem.
See more on this question at Stackoverflow