首次运行时跳过写入文件

时间:2011-01-17 15:26:42

标签: c#

我是C#的新手,并且拥有将从LogIn获取userName的代码,如果这是用户第一次登录系统,则在后台启动程序。但是,今天我注意到在运行程序并检查我的日志文件时程序跳过将数据添加到也在初始运行时创建的文件。在初始运行之后的任何运行中,userName都包含在.log文件中,如果userName与.log文件中的内容不匹配,则文件将被覆盖以包含新的userName。有人可以帮我弄清楚发生了什么或者我错过了什么吗?

提前谢谢。

 using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Diagnostics;

    namespace User
    {
        public partial class Form1 : Form
        {
            public const string dir = @"C:\Numara";
            public const string path = dir + @"\Audit.log";
            public const string TrackIT = @"C:\Program Files\Numara Software\Numara Track-It!\Track-It! Server\Audit32.exe";

            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                //returns user name
                //label1.Text = System.Environment.UserName.ToString();
                string userName = System.Environment.UserName;  //user name

                if (!Directory.Exists(dir))
                    //directory does not exist
                    //create it
                    Directory.CreateDirectory(dir);  //creates directory


                //by this point directory is created

                //now check file
                if (!File.Exists(path))
                    //file does not exist, so create it
                    File.Create(path);


                //Read data from the .log file
                string line = System.IO.File.ReadAllText(path);

                //if the name of the logged in user
                //is the same as the user name of the text file
                //then exit program

--------- the debugging stops here and skips to end the program on the first run---------

                if (line == userName) 
                    Application.Exit();

                else
                //clear fields and write new name to file and begin audit
                {
                    //clears fields
                    using (FileStream stream = new FileStream(@"C:\Numara\Audit.log", FileMode.Create))
                    {
                        using (TextWriter writer = new StreamWriter(stream))
                        {
                            //writer.Write("");
                            writer.Write(userName);
                        }
                        // writes new name to file
                    }

                      StreamReader textIn =
                      new StreamReader(
                      new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));


                    //begins audit

                    Process.Start(TrackIT, "/Q");
                    Application.Exit();
                    }        
                }
            }
        }

3 个答案:

答案 0 :(得分:3)

File.Create创建一个文件并返回一个FileStream,因此它不会关闭它。接下来您要阅读它,但它被File.Create锁定。因此会出现未处理的异常并且您的应用程序退出。第二次文件已经创建,因此它会跳过创建并锁定它。

因此您需要通过将文件放入使用块来关闭该文件: using (File.Create(path)) { }

此外,您应该将所有内容放入try catch块以处理IO异常 - 您永远不会知道是否会发生异常。

答案 1 :(得分:1)

你正在与64位调试器中的一个讨厌的bug进行战斗。在没有诊断的情况下吞下Load事件中的任何异常。解决方法是Project + Properties,Compile选项卡,Platform Target = x86。现在调试器将在异常处停止。修复它是你的下一个任务。

以防万一:避免捕获您不应处理的异常。使用try / catch 而不是通常是一个真正的解决方案。只是一个能够帮助伤害的创可贴。

答案 2 :(得分:0)

我会在第一次运行时检查userName变量和行变量的值。您也可以将其输出到日志文件中。我的猜测是,如果System.Environment.Username变量为空,那么在这种情况下你最终会退出。

另一种可能性是你没有正确处理从File.Create()引发的异常。根据File.Create()的在线文档:http://msdn.microsoft.com/en-us/library/aa328775(v=vs.71).aspx,有7种不同的异常被抛出。尝试捕获并记录这些异常,看看是否可能出现这种情况。