0
public partial class Loginform : Form
{      
    public Loginform()
    {
        InitializeComponent();
    }

    private void btnlogin_Click(object sender, EventArgs e)
    {
        string dir = "D://Login.hhh";
        if (!File.Exists(dir))
        {
            File.Create(dir);
        }

        string filePath = dir;
        string s = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
        string s1 = getIP();
        using (StreamWriter swrObj = new StreamWriter(filePath, true))
        {
            swrObj.Write(s1 + "|" + s + "|" + Txtusername.Text + "|" + "user logged in on :|" + DateTime.Now.ToShortDateString() + " at " + DateTime.Now.ToShortTimeString());
            swrObj.Write("\t\t");
            swrObj.Write("\t\t");
            swrObj.WriteLine();
            MessageBox.Show("Login success");
        }
    }

    private void Loginform_Load(object sender, EventArgs e)
    { 

    }
    private string getIP()
    { 
        IPHostEntry host;
        string localIP = "?";
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily.ToString() == "InterNetwork")
            {
                localIP = ip.ToString();
            }
        }
        return  localIP;
    }

 }

我想在 C# 中为项目应用日志文件,我使用上述方法创建用于获取系统名称、IP 地址和用户登录的日志文件,但它适用于单用户环境,如果应用在多用户环境中,如何获取所有用户的日志信息?请任何人帮助我?

4

1 回答 1

0

我假设您想为每个用户创建日志文件,那么您可以这样做:-

 private void btnlogin_Click(object sender, EventArgs e)
    {
        string s1 = getIP();
        string dir = "D://"+s1+"-"+DateTime.Now+"Login.hhh";
        if (!File.Exists(dir))
        {
            File.Create(dir);
        }

        string filePath = dir;
        string s = System.Environment.GetEnvironmentVariable("COMPUTERNAME");

        using (StreamWriter swrObj = new StreamWriter(filePath, true))
        {
            swrObj.Write(s1 + "|" + s + "|" + Txtusername.Text + "|" + "user logged in on :|" + DateTime.Now.ToShortDateString() + " at " + DateTime.Now.ToShortTimeString());
            swrObj.Write("\t\t");
            swrObj.Write("\t\t");
            swrObj.WriteLine();
            MessageBox.Show("Login success");
        }
    }
于 2012-12-22T07:41:33.463 回答