[英]How can i check if file exist and not empty then to read all lines from the file?
在新表格的顶部,我做了:
public static string AuthenticationApplicationDirectory;
public static string AuthenticationFileName = "Authentication.txt";
然后在新的表单构造函数中,我做了:
AuthenticationApplicationDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "Authentication";
if (!Directory.Exists(AuthenticationApplicationDirectory))
{
Directory.CreateDirectory(AuthenticationApplicationDirectory);
}
AuthenticationFileName = Path.Combine(AuthenticationApplicationDirectory,AuthenticationFileName);
然后在form1中加载事件:
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);
}
}
但是在form1加载事件中出现异常,即AuthenticationApplicationDirectory为null。
我想做的是一次,如果文件不存在或为空的make实例并显示新表单。
如果该文件存在并且不为空,则将其中的各行读为string []行。
问题不在于如何检查文件是否存在并且不为空然后从文件中读取所有行? 实际上,这就是为什么初始化后我的静态成员为null?
似乎您已经将用于初始化静态成员的代码放入Authentication
类构造函数中,因此在初始化Authentication
表单实例之前,该代码将不会运行,并且AuthenticationApplicationDirectory
为null。
您应该将代码放在该类的静态构造函数中:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.