我如何检查文件是否存在并且不为空,然后从文件中读取所有行
本文关键字:文件 然后 读取 何检查 检查 存在 是否 | 更新日期: 2023-09-27 18:26:10
在一个新的表单中,我做了:
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的异常。
我想做的是,如果文件不存在或为空,请创建实例并显示新表单。
如果文件存在且不为空,则将其中的行读取为字符串[]行。
问题不在如何检查文件是否存在并且不为空,然后从文件中读取所有行事实上是为什么我的静态成员在初始化时为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();
}
}