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)
- {
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2736228.html