在 C# 中刪除一個檔案
Muhammad Maisam Abbas
2024年2月16日

本教程將介紹刪除 C# 中特定路徑的檔案的方法。
在 C# 中使用 File.Delete(path)
函式刪除檔案
在 C# 中,File.Delete(path)
函式用於刪除 path
路徑內的檔案。以下程式碼示例向我們展示瞭如何使用 C# 中的 File.Delete()
函式從指定路徑刪除檔案。
using System;
using System.IO;
namespace check_whether_a_file_exists {
class Program {
static void Main(string[] args) {
string path = "C:\\filefolder\\file.txt";
bool result = File.Exists(path);
if (result == true) {
Console.WriteLine("File Found");
File.Delete(path);
Console.WriteLine("File Deleted Successfully");
} else {
Console.WriteLine("File Not Found");
}
}
}
}
輸出:
File Found
File Deleted Successfully
我們使用 C# 中的 File.Delete()
函式刪除了 C:\\filefolder\\file.txt
路徑內的檔案。我們的程式首先使用 File.Exists()
函式檢查 path
內是否存在檔案。如果檔案存在,程式將使用 File.Delete()
函式刪除該檔案。如果檔案不存在,程式將顯示 File Not Found
。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn