为什么访问文件时程序表单没有加载?

时间:2014-01-28 21:33:18

标签: c# winforms file

使用下面的代码,我已经测试了它并且表单的加载工作正常,但是当程序检查文件是否存在时,表单无法正确加载,我不知所措至于做什么。是否有另一种方法来检查是否存在我可以在此实例中使用的文件?

编辑我已经制作了一个新的'启动'表单来运行文件存在检查,但它仍然无法正常工作。表单再次加载,但表单的内容没有加载,表单本身也会冻结。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Diagnostics;
using System.Windows.Input;

namespace program1
{
    public partial class Startup : Form
    {
        public Startup()
        {
            InitializeComponent();

        }

        private void Startup_Load(object sender, EventArgs e)
        {
            notifyIcons norm = new notifyIcons();
            Settings set = new Settings();
            set.Show();
            string curFile = Environment.CurrentDirectory + "\\age.txt";
            if (File.Exists(curFile))
            {
                norm.Show();
                this.Close();
            }
            else
            {
                set.Show();
                for (;;) 
                {
                    if (File.Exists(curFile)) norm.Show(); this.Close();
                    Application.DoEvents();
                }
            }
         }
        }
    }

3 个答案:

答案 0 :(得分:4)

我不知道这段代码应该做什么..但我可以告诉你它为什么不起作用。

while (ageFileExists)

这绝不是假的。因此,你的循环将不断循环......永远。你需要在循环中以某种方式将其设置为false。我不知道是什么类型的规则来管理它。

表单没有加载的原因是因为循环永远不会退出..因此使窗口执行任何的消息循环永远不会继续处理窗口消息。

如果您可以提供更多关于您尝试做的事情的背景信息,我可以帮助您找到合适的解决方案。尽管如此,我只能看到问题。

答案 1 :(得分:0)

while(ageFileExists)
{
    if (File.Exists(curFile)) ageFileExists = true;
    set.WindowState = FormWindowState.Normal;
}

如果该文件存在,则您有一个无限循环。您从未将ageFileExists设置为false,并且该循环根本不执行任何操作。那个标签在哪里?我严重怀疑你需要使用goto。你的代码没有多大意义。

答案 2 :(得分:0)

通过在主窗体中使用以下代码,它似乎是一种享受!我认为关键部分是Application.DoEvents(); 感谢您的所有帮助

InitializeComponent();
            set.Show();
            set.WindowState = FormWindowState.Minimized;

            string curFile = Environment.CurrentDirectory + "\\age.txt";
            if (File.Exists(curFile)) goto Labelx;
            set.WindowState = FormWindowState.Normal;
            for (; ; ) { Application.DoEvents(); if (File.Exists(curFile)) break; }
            set.WindowState = FormWindowState.Minimized;
            Labelx:TextReader reader = File.OpenText(Environment.CurrentDirectory + "\\age.txt");