天天看點

檔案和檔案夾的操作——檔案夾的操作

建立檔案夾

檔案和檔案夾的操作——檔案夾的操作

建立檔案夾主要使用Directory類的Create方法

 private void button1_Click(object sender, EventArgs e)

       {

           FolderBrowserDialog FBDialog = new FolderBrowserDialog();//建立FolderBrowserDialog對象

           if (FBDialog.ShowDialog() == DialogResult.OK)//判斷是否選擇檔案夾

           {

               string strPath = FBDialog.SelectedPath;//記錄選擇的檔案夾

               if (strPath.EndsWith("\\"))

                   textBox1.Text = strPath;//顯示選擇的檔案夾

               else

                   textBox1.Text = strPath + "\\";

           }

       }

       private void button2_Click(object sender, EventArgs e)

           DirectoryInfo DInfo = new DirectoryInfo(textBox1.Text + textBox2.Text);//建立DirectoryInfo對象

           DInfo.Create();//建立檔案夾

删除檔案夾

檔案和檔案夾的操作——檔案夾的操作

思路:删除檔案夾主要用到了DirectoryInfo類的Delete方法,文法如下:

public override void Delete();

public void Delete(bool recursive);

轉存失敗重新上傳取消 參數說明:若為true,則删除該檔案夾及其子檔案夾和所有檔案,否則為false。

例:

public partial class Frm_Main : Form

   {

       public Frm_Main()

           InitializeComponent();

       private void button1_Click(object sender, EventArgs e)

           if (FBDialog.ShowDialog() == DialogResult.OK)//判斷是否選擇了檔案夾

               textBox1.Text = FBDialog.SelectedPath;//顯示選擇的檔案夾

           DirectoryInfo DInfo = new DirectoryInfo(textBox1.Text);//建立DirectoryInfo對象

           DInfo.Delete(true);//删除檔案夾所有内容

           MessageBox.Show("删除檔案夾成功!");

}

注:Directory類和DirectoryInfo類的差別:Directory是靜态類,是以他的調用需要字元串參數為每一個方法調用規定檔案夾路徑,是以如果要在對象上進行單一方法調用,則可以使用靜态Directory類,在這種情況下靜态調用的速度要快一些,因為.Net架構不必執行執行個體化對象并調用其方法的過程。如果在檔案夾上執行幾種操作,則建立DirectoryInfo對象并是用其方法就更好一些,這樣會提高效率,因為對象在檔案夾上引用正确的檔案夾,而靜态類就必須每次都尋找檔案夾。

擷取所有邏輯磁盤目錄

思路:擷取計算機中的所有邏輯分區,主要通過Directory類的GetLogicalDrives方法實作,然後擷取邏輯分區下所有自問佳佳和檔案,通過Directory類的GetDirectories方法和GetFiles方法實作。

(1)、GetLogicalDrives方法:檢索計算機上邏輯分區的名稱。文法如下:

public static string[] GetLogicalDrivers()

(2)、GetDirectories方法:該方法用來擷取指定檔案夾中子檔案夾的名稱。文法如下:

public static String[] GetDirectries(string path)

參數說明:path為其傳回子檔案夾名稱的數組的路徑。

傳回值:一個類型String的數組,他包含path中子檔案夾的名稱。

(3)、GetFiles方法 該方法傳回指定檔案夾的檔案的名稱。文法如下:

public static string[] GetFiles(string path)

參數說明:path将從其檢索檔案的檔案夾

傳回值:指定檔案夾中檔案名得 String數組。

 public void listFolders(ToolStripComboBox tscb)//擷取本地磁盤目錄

           string[] logicdrives = System.IO.Directory.GetLogicalDrives();

           for (int i = 0; i < logicdrives.Length; i++)

               tscb.Items.Add(logicdrives[i]);

               tscb.SelectedIndex = 0;

繼續閱讀