C#获得文件属性信息的实现方法
本文实例演示了用VisualC#获取任意文件的属性信息,这些属性信息包括文件名、创建时间、访问时间、最后写入时间等等。本实例需要用到FileInfo类。FileInfo类用于提供创建、复制、删除、移动和打开文件的实例方法,并且帮助创建FileStream对象。
主要功能代码如下:
usingSystem;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Windows.Forms;
usingSystem.Data;
usingSystem.IO;
namespace获取文件属性
{
publicclassForm1:System.Windows.Forms.Form
{
privateSystem.Windows.Forms.ListBoxlistBox1;
privateSystem.Windows.Forms.Buttonbutton1;
privateSystem.Windows.Forms.OpenFileDialogopenFileDialog1;
privateSystem.ComponentModel.Containercomponents=null;
publicvoidAddItem(stringsItem)
{
listBox1.Items.Add(sItem);//添加项sItem到listBox1中
}
publicForm1()
{
InitializeComponent();
}
protectedoverridevoidDispose(booldisposing)
{
if(disposing)
{
if(components!=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#regionWindows窗体设计器生成的代码
privatevoidInitializeComponent()
{
this.listBox1=newSystem.Windows.Forms.ListBox();
this.button1=newSystem.Windows.Forms.Button();
this.openFileDialog1=newSystem.Windows.Forms.OpenFileDialog();
this.SuspendLayout();
//listBox1
this.listBox1.ItemHeight=12;
this.listBox1.Location=newSystem.Drawing.Point(8,56);
this.listBox1.Name="listBox1";
this.listBox1.Size=newSystem.Drawing.Size(272,208);
this.listBox1.TabIndex=0;
//button1
this.button1.Location=newSystem.Drawing.Point(96,8);
this.button1.Name="button1";
this.button1.Size=newSystem.Drawing.Size(96,32);
this.button1.TabIndex=1;
this.button1.Text="请选择文件";
this.button1.Click+=newSystem.EventHandler(this.button1_Click);
//Form1
this.AutoScaleBaseSize=newSystem.Drawing.Size(6,14);
this.ClientSize=newSystem.Drawing.Size(292,273);
this.Controls.Add(this.button1);
this.Controls.Add(this.listBox1);
this.Name="Form1";
this.Text="获取文件属性";
this.ResumeLayout(false);
}
#endregion
[STAThread]
staticvoidMain()
{
Application.Run(newForm1());
}
privatevoidbutton1_Click(objectsender,System.EventArgse)
{
if(this.openFileDialog1.ShowDialog()==DialogResult.OK)
{
//清除listBox1中所有的项
listBox1.Items.Clear();
FileInfofile=newFileInfo(this.openFileDialog1.FileName);
//向ListBox中一次添加一个项,通过防止该控件绘图来维护性能,
//直到调用EndUpdate方法为止
listBox1.BeginUpdate();
//获取文件名
AddItem("文件名:"+file.Name);
//获取文件的长度
AddItem("文件长度(bytes):"+file.Length);
//获取当前FileSystemInfo对象的创建时间
AddItem("创建时间:"+file.CreationTime.ToString());
//获取上次访问当前文件或目录的时间
AddItem("最后访问时间:"+file.LastAccessTime.ToString());
//获取上次写入当前文件或目录的时间
AddItem("最后写入时间:"+file.LastWriteTime.ToString());
listBox1.EndUpdate();
}
}
}
}
本例演示了功能代码的主体部分,读者可以根据自己的要求进一步完善其窗体界面与功能。