如何检查文件是否存在而不是空,然后从文件中读取所有行?

时间:2015-12-07 18:00:13

标签: c# .net winforms

在新表单中我做了:

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。

我想要做的是,如果文件不存在或者为空,则生成实例并显示新表单。

如果文件存在且不为空,则将其中的行读入字符串[]行。

1 个答案:

答案 0 :(得分:2)

问题不是我如何检查文件是否存在而不是空,然后从文件中读取所有行?实际上它是为什么我的静态成员在我初始化时为空它吗

您似乎已经在Authentication类构造函数中放置了初始化静态成员的代码,因此在初始化Authentication表单的实例之前,该代码将无法运行并AuthenticationApplicationDirectory是空的。

您应该将代码放在该类的静态构造函数中:

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();
    }
}
相关问题