天天看點

Csharp進階:檔案流之Directory類和DirectoryInfo類,FileStream 類

Directory類和DirectoryInfo類

在程式開發中,不僅需要對檔案進行操作,而且還需要對檔案目錄進行操作。例如建立目錄,删除目錄等,為此C#提供了Directory類和DirectoryInfo類。

******************************

Directory類是靜态類,提供了許多靜态方法用于對目錄進行操作,例如建立、删除、查詢和移動目錄等。

靜态方法,在指定目錄建立所有目錄和子目錄

Directory.CreateDirectory(path);

******************************

DirectoryInfo類的功能與Directory類相似,不同的是DirectoryInfo是一個執行個體類,該類不僅擁有與Directory類功能相似的方法,而且還具有一些特有的屬性。

執行個體方法,檢索指定的父目錄

DirectoryInfo di = Directory.GetParent(path);

FileStream 類

FileStream 類表示在磁盤或網絡路徑上指向檔案的流,并提供了在檔案中讀寫位元組和位元組數組的方法,通過這些方法,FileStream 對象可以讀取諸如圖像、聲音、視訊、文本檔案等,也就是說FileStream類能夠處理各種資料檔案。

FileStream類有很多重載的構造方法,其中最常用的是帶有三個參數的構造方法,具體如下。

FileStream(stringpath, FileMode mode, FileAccess access);

上述構造方法中,第一個參數path表示的是檔案路徑名,第二個參數mode表示如何打開或建立檔案,第三個參數access用于确定 FileStream 對象通路檔案的方式。

建立一個是否有此檔案(沒有則建立有則打開),并從中讀取資料的執行個體檔案流。

fsRead=new FileStream(sourcePath,FileMode.OpenOrCreate, FileAccess.Read);

建立一個是否有此檔案(沒有則建立有則打開)并向其中寫入資料的執行個體檔案流。

fsWrite= new FileStream(destPath, FileMode.OpenOrCreate, FileAccess.Write);

搭配使用使第一個檔案的資料以位元組為機關全部寫入第二個檔案

int temp = -1;

while ((temp = fsRead.ReadByte()) != -1)

{

fsWrite.WriteByte((byte)temp)

}

資料流通常與try-catch-catch-finally搭配尋找異常的執行個體

FileStream fsRead = null;

            FileStream fsWrite = null;

            try

            {

                fsRead = new FileStream(sourcePath, FileMode.OpenOrCreate, FileAccess.Read);

                fsWrite = new FileStream(destPath, FileMode.OpenOrCreate, FileAccess.Write);

                int temp = -1;

                while ((temp = fsRead.ReadByte()) != -1)

                {

                    fsWrite.WriteByte((byte)temp);

                }

            } 

            catch(IOException e)(IO異常)

            {

                Console.WriteLine(e.Message);

            }         

            catch(Exception e)(其他異常)

            {

                Console.WriteLine(e.Message);

            }

            finally

            {

                fsRead.Close();

                fsWrite.Close();

            }