■■■

2016年4月8日金曜日

読み取り専用属性でも強制的にファイルを削除する方法

読み取り専用属性でも強制的にファイルを削除する方法
VB.NET
        ' 1.ファイルを削除する
        System.IO.File.Delete("C:\del.txt")


        ' 2.ファイルを強制的に削除する方法
        Dim strFilePath As [String] = "c:\delete.txt"
        Dim fiDelete As New System.IO.FileInfo(strFilePath)
        ' ファイルの存在確認をしておく
        If fiDelete.Exists Then
            ' 読み取り専用を解除
            If (fiDelete.Attributes And System.IO.FileAttributes.[ReadOnly]) = System.IO.FileAttributes.[ReadOnly] Then
                fiDelete.Attributes = System.IO.FileAttributes.Normal
            End If

            ' 削除
            fiDelete.Delete()

        End If

C#
            // 1.ファイルを削除する
            System.IO.File.Delete(@"C:\del.txt");


            // 2.ファイルを強制的に削除する方法
            String strFilePath = @"c:\delete.txt";
            System.IO.FileInfo fiDelete = new System.IO.FileInfo(strFilePath);
            // ファイルの存在確認をしておく
            if (fiDelete.Exists)
            {
                // 読み取り専用を解除
                if ((fiDelete.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
                {
                    fiDelete.Attributes = System.IO.FileAttributes.Normal;
                }

                // 削除
                fiDelete.Delete();

            }

■■■