當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# File.Delete()用法及代碼示例

File.Delete(String)是一個內置的File類方法,該方法用於刪除指定的文件。

用法:

public static void Delete (string path);

參數:該函數接受如下所示的參數:



  • path: This is the specified file path which is to be deleted.

異常:

  • ArgumentException:路徑為長度為零的字符串,僅包含空格,或者由InvalidPathChars定義的一個或多個無效字符。
  • ArgumentNullException:路徑為空。
  • DirectoryNotFoundException:給定的路徑無效。
  • IOException:給定的文件正在使用中。或者文件上有打開的句柄,並且操作係統是Windows XP或更早版本。枚舉目錄和文件可能會導致此打開的句柄。有關更多信息,請參見如何:枚舉目錄和文件。
  • NotSupportedException:路徑格式無效。
  • PathTooLongException:給定的路徑,文件名或兩者都超過了system-defined的最大長度。
  • UnauthorizedAccessException:調用者沒有所需的權限。或者該文件是正在使用的可執行文件。或路徑是目錄。或路徑指定了一個隻讀文件。

下麵是說明File.Delete(String)方法的程序。

程序1:在運行下麵的代碼之前,將創建一個文件file.txt,其內容如下所示:

file.txt

// C# program to illustrate the usage 
// of File.Delete(String) method 
  
// Using System and System.IO namespaces 
using System; 
using System.IO; 
  
public class GFG { 
    // Using main() function 
    public static void Main() 
    { 
        // Specifing a file 
        String myfile = @"file.txt"; 
  
        // Calling the Delete() function to 
        // delete the file file.txt 
        File.Delete(myfile); 
  
        // Printing a line 
        Console.WriteLine("Specified file has been deleted"); 
    } 
}

執行中:

mcs -out:main.exe main.cs
mono main.exe
Specified file has been deleted

運行上述代碼後,將顯示以上輸出,並且文件file.txt已被刪除。

程序2:在運行以下代碼之前,已創建兩個文件,如下所示:

file.txt

gfg.txt

// C# program to illustrate the usage 
// of File.Delete(String) method 
  
// Using System and System.IO namespaces 
using System; 
using System.IO; 
  
public class GFG { 
    // Using main() function 
    public static void Main() 
    { 
        // Specifing two files 
        String myfile1 = @"file.txt"; 
        String myfile2 = @"gfg.txt"; 
  
        // Calling the Delete() function to 
        // delete the file file.txt and gfg.txt 
        File.Delete(myfile1); 
        File.Delete(myfile2); 
  
        // Printing a line 
        Console.WriteLine("Specified files have been deleted."); 
    } 
}

執行中:

mcs -out:main.exe main.cs
mono main.exe
Specified files have been deleted.

運行以上代碼後,將顯示以上輸出,並且刪除了兩個現有文件file.txt和gfg.txt。




相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 File.Delete() Method in C# with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。