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.Xml.Serialization;
using System.IO;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string pathname = "sysdatetime.xml"; // 文件路径
/// <summary>
/// 窗体打开的时候反序列化 取得上次关闭时间
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
// 判断文件是否存在
if (File.Exists(pathname))
{
SystemDateTime myObject;
XmlSerializer mySerializer =
new XmlSerializer(typeof(SystemDateTime));
FileStream myFileStream =
new FileStream(pathname, FileMode.Open);
myObject = (SystemDateTime)mySerializer.Deserialize(myFileStream);
myFileStream.Close();
myFileStream.Dispose();
this.label1.Text = myObject.SystemDate.ToString("yyyy-MM-dd HH:mm:ss ffff");
}
}
/// <summary>
/// Windows 窗体关闭的时候序列化保存当前时间
/// </summary>
/// <param name="e"></param>
protected override void OnClosed(EventArgs e)
{
SystemDateTime myObject = new SystemDateTime();
myObject.SystemDate = DateTime.Now; // 设置当前时间
XmlSerializer mySerializer = new
XmlSerializer(typeof(SystemDateTime));
StreamWriter myWriter = new StreamWriter(pathname);
mySerializer.Serialize(myWriter, myObject);
myWriter.Close();
base.OnClosed(e);
}
}
/// <summary>
/// 保存时间的实体类
/// </summary>
[Serializable]
public class SystemDateTime
{
public DateTime SystemDate { get; set; }
}
}
每一次登录的时候都往数据库中插入一条记录,记录下当前的系统时间,然后下次登录的时候取出id最大的那条记录,把时间显示出来就行了。
如果仅仅是显示上次运行时间,可以把上次启动的时间写到一个本地文件中, 这个文件可以是.txt,xml等格式,然后每次运行时读取这个文件的值就可以了,不必写到数据库
具体可参考 ".net中如何读写文件"找相关资料