Reputation: 277
In a new form top i did:
public static string AuthenticationApplicationDirectory;
public static string AuthenticationFileName = "Authentication.txt";
Then in the new form constructor i did:
AuthenticationApplicationDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "Authentication";
if (!Directory.Exists(AuthenticationApplicationDirectory))
{
Directory.CreateDirectory(AuthenticationApplicationDirectory);
}
AuthenticationFileName = Path.Combine(AuthenticationApplicationDirectory,AuthenticationFileName);
Then in form1 Load event:
private void Form1_Load(object sender, EventArgs e)
{
Authentication.AuthenticationFileName = Path.Combine(Authentication.
AuthenticationApplicationDirectory, Authentication.AuthenticationFileName);
if (File.Exists(Authentication.AuthenticationFileName) &&
new FileInfo(Authentication.AuthenticationFileName).Length != 0)
{
string[] lines = File.ReadAllLines(Authentication.AuthenticationFileName);
}
else
{
Authentication auth = new Authentication();
auth.Show(this);
}
}
But getting exception in form1 load event that AuthenticationApplicationDirectory is null.
What i want to do is once if the file not exist or empty make instance and show the new form.
If the file exist and not empty then read the lines from it into string[] lines.
Upvotes: 0
Views: 806
Reputation: 125302
The problem is not How can I check if file exist and not empty then to read all lines from the file? in fact it is Why my static member is null while I have initialized it?
It seems you have put the code that initializes your static members in the Authentication
class constructor, so before you initialize an instance of Authentication
form, that code will not run and AuthenticationApplicationDirectory
is null.
You should put your codes in static constructor of that class:
public class Authentication : Form
{
public static string AuthenticationApplicationDirectory;
public static string AuthenticationFileName = "Authentication.txt";
static Authentication()
{
AuthenticationApplicationDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "Authentication";
if (!Directory.Exists(AuthenticationApplicationDirectory))
{
Directory.CreateDirectory(AuthenticationApplicationDirectory);
}
AuthenticationFileName = Path.Combine(AuthenticationApplicationDirectory, AuthenticationFileName);
}
public Authentication()
{
InitializeComponent();
}
}
Upvotes: 2