【问题标题】:C# Form doesn't loadC# 表单不加载
【发布时间】:2015-07-09 14:50:30
【问题描述】:

如果我有这段代码,我的表单不会加载

 private void Form1_Load(object sender, EventArgs e)
    {
           // Variables
        string currentDirectory = Directory.GetCurrentDirectory();
        string checkFile = ("mailingdir\\check.txt");
        bool newFolder = (File.Exists(checkFile));

        if (newFolder)
            {
                 newFolder = true;
            }
        else
            {
                 newFolder = false;
                 File.Create("mailingdir\\check.txt");
            }

如果我注释掉 File.Create("mailingdir\\check.txt");,它会立即加载。

我只是在尝试,所以我认为我犯了一个初学者的错误。

【问题讨论】:

  • 那只是存根代码,我会删除它。谢谢
  • 另外,当 newFolder 在声明时已经评估了一个表达式时,在 IF/ELSE 中分配一个值有什么意义?这与bool b = true; if (b) b = true; 相同
  • 那只是为了填补 if true 声明
  • 嗯?如果您稍后在代码中实际上没有使用newFolder,那么您不需要变量。你可以简单地做IF (!Folder.Exists(checkFile)) { File.Create(someString); }

标签: c# forms winforms load


【解决方案1】:

只要路径存在,上面的代码就可以完美运行。将“mailingdir”替换为点,这样它将引用应用程序的位置。 exe所在的位置好像没有“mailingdir”。

private void Form1_Load(object sender, EventArgs e)
    {
        string currentDirectory = Directory.GetCurrentDirectory();
        string workingDirectoryPlus1 = (currentDirectory + 1);
        string checkFile = (".\\check.txt");
        bool newFolder = (File.Exists(checkFile));

        if (newFolder)
        {
            newFolder = true;
        }
        else
        {
            newFolder = false;
            File.Create(".\\check.txt");
        }
    }

【讨论】:

  • 感谢您的回答。 “check.txt”文件需要在 mailingdir 文件夹中创建,它不在您的代码中吗?编辑:没关系,你是对的。谢谢!
  • 还有一个提示。您需要在解决方案中的“mailingdir”中至少有一个带有构建操作“copy”的文件,否则将不会创建目录进行调试。
【解决方案2】:

您的代码给出了 DirectoryNotFoundException,因为 mailingdir 不存在。

您必须先创建目录,然后再创建文件。

Directory.CreateDirectory("mailingdir");
File.Create("mailingdir\\check.txt");

【讨论】:

    猜你喜欢
    • 2012-09-03
    • 2013-02-12
    • 1970-01-01
    • 2018-12-03
    • 2017-02-18
    • 1970-01-01
    • 2011-08-24
    • 2014-08-30
    • 1970-01-01
    相关资源
    最近更新 更多