File类和Directory类

File类和Directory类分别用来对文件和各种目录进行操作,这两类可以被实例化,但不能被其他类集成。

1. File类(静态类)

File类支持对文件的基本操作,它包括用于创建、复制、删除、移动和打开文件的静态方法,并协助创建FileStream对象。

2. Directory类(静态类)

Directory类公开了用于创建、移动、枚举、删除目录和子目录的静态方法。

 

举例1:文件的创建

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 Test01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

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

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

举例2:文件夹的创建

 

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 Test02
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

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

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

 

posted @ 2018-08-21 12:55  fsspring  阅读(1581)  评论(0编辑  收藏  举报