FileInfo类和DirectoryInfo类

FileInfo类和DirectoryInfo类可以方便地对文件和文件夹进行操作。

1. FileInfo类(非静态类)

FileInfo类和File类之间许多方法调用都是相同的,但是FileInfo类没有静态方法,但类中的方法仅可以用于实例化的对象。

2. DirectoryInfo类(非静态类)

DirectoryInfo类和Directory类之间的关系与FileInfo类和File类之间的关系十分类似,这里不再赘述。

 

举例 FileInfo类如下,需创建实例才能用。

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

namespace Test03
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == string.Empty)           //判断输入的文件名称是否为空
            {
                MessageBox.Show("文件名称不能为空!");
            }
            else
            {
                FileInfo finfo = new FileInfo(textBox1.Text);
                if (finfo.Exists)                        //使用FileInfo对象的Exists属性判断要创建的文件是否存在
                {
                    MessageBox.Show("该文件已经存在");
                }
                else
                {
                    finfo.Create();                       //使用FileInfo对象的Create方法创建文件
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

 

posted @ 2018-08-21 13:27  fsspring  阅读(220)  评论(0编辑  收藏  举报