日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#如何刪除指定文件或文件夾_C#教程

作者:江斌先生 ? 更新時間: 2023-03-20 編程語言

C#刪除指定文件或文件夾

public static string deleteOneFile(string fileFullPath)
        {
            // 1、首先判斷文件或者文件路徑是否存在
            if (Directory.Exists(fileFullPath))
            {
                // 2、根據路徑字符串判斷是文件還是文件夾
                FileAttributes attr = File.GetAttributes(fileFullPath);
                // 3、根據具體類型進行刪除
                if (attr == FileAttributes.Directory)
                {
                    Directory.Delete(fileFullPath, true); // 3.1、刪除文件夾
                }
                else
                {
                    File.Delete(fileFullPath);// 3.2、刪除文件
                }
                File.Delete(fileFullPath);
                return "刪除成功:" + fileFullPath;
            }
            return "無該文件或文件夾:" + fileFullPath;
        }

注意:

1.正常該定義為bool返回,由于我這邊需要反饋到前端,所以直接使用了string返回.

2.實際使用中最好加個try catch拋出異常

C#根據路徑刪除文件或文件夾

如何根據路徑刪除文件或文件夾?

1.首先我們要判斷路徑是文件或者是文件夾

那么我們可以通過?FileAttributes attr = File.GetAttributes(path); 來得到路徑的屬性

在判斷屬性是否是FileAttributes.Directory

完整代碼

    /// <summary>
    /// 根據路徑刪除文件
    /// </summary>
    /// <param name="path"></param>
    public void DeleteFile(string path)
    {
        FileAttributes attr = File.GetAttributes(path);
        if (attr == FileAttributes.Directory)
        {
            Directory.Delete(path, true);
        }
        else
        {
            File.Delete(path);
        }
    }

總結

原文鏈接:https://blog.csdn.net/jiangbin881/article/details/124444606

欄目分類
最近更新