I am new to C# and have code that will obtain the userName from the LogIn and begin a program in the background if this is the users first time loging into the system. However, today I noticed when running the program and checking my log file that the program skips adding data to the file that is also created on the initial run. Any run after the initial run, the userName is included into the .log file and if the userName does not match what is in the .log file the file is overwritten to include the new userName. Can someone please help me figure out what happened or if I’m missing something?
Thank you in advance.
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();
}
}
}
}
File.Createcreates a file and returns a FileStream, so it does not close it. Next you want to read it, but it is locked by theFile.Create. So exception appears which is not handled and your application quits. Second times the file is already created, so it skips creating and locking it.So you need to close the file by putting it into using block:
using (File.Create(path))
{
}
Also, you should put all the stuff into
try catchblocks to handle IO exceptions – you can never know if one occurs.