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)
        {

        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM