Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)

<< < (114/120) > >>

Elektro Enjuto:
Un algoritmo para volcar un texto de forma vertical.

Inspirado en este servicio: https://onlinetexttools.com/flip-text-vertically

Los resultados son idénticos o muy similares a estos:




UtilString.vb
Código
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 11-July-2023
' ***********************************************************************
 
#Region " Public Members Summary "
 
#Region " Functions "
 
' FlipTextVertically(String, VerticalFlipTextMode, Opt: Char) As String
 
#End Region
 
#End Region
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Linq
Imports System.Text
 
#End Region
 
#Region " String Util "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Core.DataProcessing.Common
 
   Partial Public NotInheritable Class UtilString
 
#Region " Public Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Transforms the source string into vertical text.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <seealso href="https://onlinetexttools.com/flip-text-vertically"/>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="input">
       ''' The input string to flip it vertically.
       ''' <para></para>
       ''' If this value is null, no changes are made to the string.
       ''' </param>
       '''
       ''' <param name="flipMode">
       ''' The vertical flip mode indicating how the text should be flipped.
       ''' </param>
       '''
       ''' <param name="separatorChar">
       ''' Optional. The character used to separate columns. Default is "|".
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The resulting vertically flipped text.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Public Shared Function FlipTextVertically(input As String, flipMode As VerticalFlipTextMode,
                                                 Optional separatorChar As Char = "|"c) As String
 
           If String.IsNullOrEmpty(input) Then
               Return input
           End If
 
           If separatorChar.Equals(Nothing) Then
               Throw New ArgumentNullException(paramName:=NameOf(separatorChar))
           End If
 
           Select Case flipMode
 
               Case VerticalFlipTextMode.CharByChar
                   Dim lines As String() = input.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
                   Dim maxLength As Integer = lines.Max(Function(line) line.Length)
                   Dim verticalText As New StringBuilder()
                   For i As Integer = 0 To maxLength - 1
                       For j As Integer = 0 To lines.Length - 1
                           If i < lines(j).Length Then
                               verticalText.Append(lines(j)(i))
                           Else
                               verticalText.Append(" "c)
                           End If
                           If j < lines.Length - 1 Then
                               verticalText.Append($" {separatorChar} ")
                           End If
                       Next
                       verticalText.AppendLine()
                   Next
                   Return verticalText.ToString()
 
               Case VerticalFlipTextMode.WordByWord
                   Dim lines As String() = input.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
                   Dim wordsPerLine As New List(Of List(Of String))()
                   For Each line As String In lines
                       Dim words As String() = line.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
                       wordsPerLine.Add(words.ToList())
                   Next
                   Dim maxLength As Integer = wordsPerLine.Max(Function(words) words.Count)
                   Dim verticalText As New StringBuilder()
                   For i As Integer = 0 To maxLength - 1
                       For j As Integer = 0 To wordsPerLine.Count - 1
                           Dim words As List(Of String) = wordsPerLine(j)
                           If i < words.Count Then
                               verticalText.Append(words(i).PadRight(words.Max(Function(word) word.Length)))
                           Else
                               verticalText.Append(" ".PadRight(words.Max(Function(word) word.Length)))
                           End If
                           If j < wordsPerLine.Count - 1 Then
                               verticalText.Append($" {separatorChar} ")
                           End If
                       Next
                       verticalText.AppendLine()
                   Next
                   Return verticalText.ToString()
 
               Case VerticalFlipTextMode.SentenceBySentence
                   Dim GetMaxSentences As Func(Of String(), Integer) =
                   Function(_lines As String()) As Integer
                       Dim _maxSentences As Integer = 0
                       For Each line As String In _lines
                           Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries)
                           _maxSentences = System.Math.Max(_maxSentences, sentences.Length)
                       Next
                       Return _maxSentences
                   End Function
 
                   Dim GetColumnWidths As Func(Of String(), Integer, Integer()) =
                   Function(_lines As String(), _maxSentences As Integer) As Integer()
                       Dim _columnWidths As Integer() = New Integer(_lines.Length - 1) {}
                       For i As Integer = 0 To _lines.Length - 1
                           Dim line As String = _lines(i)
                           Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries)
                           Dim maxWidth As Integer = 0
                           For j As Integer = 0 To System.Math.Min(_maxSentences, sentences.Length) - 1
                               maxWidth = System.Math.Max(maxWidth, sentences(j).Trim().Length)
                           Next
                           _columnWidths(i) = maxWidth
                       Next
                       Return _columnWidths
                   End Function
 
                   Dim lines As String() = input.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
                   Dim maxSentences As Integer = GetMaxSentences(lines)
                   Dim columnWidths As Integer() = GetColumnWidths(lines, maxSentences)
                   Dim output As New StringBuilder()
 
                   For i As Integer = 0 To maxSentences - 1
                       For j As Integer = 0 To lines.Length - 1
                           Dim line As String = lines(j)
                           Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries)
                           Dim sentence As String = ""
                           If i < sentences.Length Then
                               sentence = sentences(i).Trim() & "."
                           End If
                           Dim column As String = sentence.PadRight(columnWidths(j) + 1)
                           output.Append(column)
                           If j < lines.Length - 1 Then
                               output.Append($" {separatorChar} ")
                           End If
                       Next
                       output.AppendLine()
                   Next
                   Return output.ToString()
 
               Case Else
                   Throw New InvalidEnumArgumentException(argumentName:=NameOf(flipMode), invalidValue:=flipMode, enumClass:=GetType(VerticalFlipTextMode))
 
           End Select
 
       End Function
 
#End Region
 
   End Class
 
End Namespace
 
#End Region
 


VerticalFlipTextMode.vb
Código
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 11-July-2023
' ***********************************************************************
 
#Region " Option Statements "
 
Option Strict Off
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
#End Region
 
#Region " VerticalFlipTextMode "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Core.DataProcessing.Common
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Specifies how the text should be flipped when using <see cref="UtilString.FlipTextVertically"/> function.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   Public Enum VerticalFlipTextMode As Integer
 
       ''' <summary>
       ''' Divides the text into characters.        
       ''' That is, all the characters from every text row get rearranged in columns.
       ''' </summary>
       CharByChar
 
       ''' <summary>
       ''' Divides the text into words.
       ''' <para></para>
       ''' That is, all the words from every text row get rearranged in columns.
       ''' </summary>
       WordByWord
 
       ''' <summary>
       ''' Divides the text into sentences.
       ''' <para></para>
       ''' That is, if you have several sentences in one line,
       ''' then after rewriting them vertically, they will appear in a single column.
       ''' </summary>
       SentenceBySentence
 
   End Enum
 
End Namespace
 
#End Region
 

Elektro Enjuto:
Un algoritmo para envolver de forma decorativa los caracteres de un string.

Inspirado en este servicio: https://onlinetexttools.com/add-symbols-around-letters

Los resultados son idénticos o muy similares a esto:



...con opciones de personalización.


Código
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 11-July-2023
' ***********************************************************************
 
#Region " Public Members Summary "
 
#Region " Functions "
 
' WrapCharacters(String, Char, Char, Opt: Boolean, Opt: Boolean) As String
 
#End Region
 
#End Region
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports System.Linq
Imports System.Text
 
#End Region
 
#Region " String Util "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Core.DataProcessing.Common
 
   Partial Public NotInheritable Class UtilString
 
#Region " Public Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Decorates the input string by wrapping each character with the specified decorative symbols
       ''' for its left and right sides.
       ''' <para></para>
       ''' For example, if the input string is 'ABC', the resulting string could be similar to this: '{A}{B}{C}'.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="input">
       ''' The input string to decorate.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="leftChar">
       ''' The character used for decorating the left side of the characters in the input string.
       ''' </param>
       '''
       ''' <param name="rightChar">
       ''' The character used for decorating the right side of the characters in the input string.
       ''' </param>
       '''
       ''' <param name="surroundNonAlphanumeric">
       ''' If true, also decorates non-alphanumeric characters.
       ''' <para></para>
       ''' Default value is: False.
       ''' </param>
       '''
       ''' <param name="squishRepeatedDecorationChars">
       ''' If true, and if <paramref name="leftChar"/> and <paramref name="rightChar"/> are the same characters,
       ''' only draws the decorative symbol for the left side of the characters in the input string.
       ''' <para></para>
       ''' Default value is: False.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The resulting decorated string.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Public Shared Function WrapCharacters(input As String, leftChar As Char, rightChar As Char,
                                             Optional surroundNonAlphanumeric As Boolean = False,
                                             Optional squishRepeatedDecorationChars As Boolean = False) As String
 
           If String.IsNullOrEmpty(input) Then
               Throw New ArgumentNullException(paramName:=NameOf(input))
           End If
 
           If leftChar.Equals(Nothing) Then
               Throw New ArgumentNullException(paramName:=NameOf(leftChar))
           End If
 
           If rightChar.Equals(Nothing) Then
               Throw New ArgumentNullException(paramName:=NameOf(rightChar))
           End If
 
           Dim areSameDecorationChars As Boolean = (leftChar = rightChar)
 
           Dim sb As New StringBuilder()
           For Each c As Char In input
               Dim decoratedChar As String =
               If(Char.IsLetterOrDigit(c) OrElse (surroundNonAlphanumeric AndAlso Not Char.IsWhiteSpace(c)),
                  If(squishRepeatedDecorationChars AndAlso areSameDecorationChars,
                     $"{leftChar}{c}",
                     $"{leftChar}{c}{rightChar}"),
                  c)
 
               sb.Append(decoratedChar)
           Next
 
           Return sb.ToString()
       End Function
 
#End Region
 
   End Class
 
End Namespace
 
#End Region
 
 

Elektro Enjuto:
Un algoritmo para dibujar cajas unicode envolviendo un texto. Útil para decorar la interfaz de aplicaciones de consola.

Inspirado en este servicio: https://onlinetexttools.com/draw-box-around-text
( el resultado debería ser idéntico. )

Ejemplo de uso:

Código
Dim input As String = "Push this button!"
Dim verticalPadding As Integer = 1
Dim horizontalPadding As Integer = 2
Dim fillChar As Char = "&#9608;"c
Dim drawingStyle As New BoxDrawingStyle With {
       .Top = "&#9552;"c, .Bottom = "&#9552;"c,
       .Left = "&#9553;"c, .Right = "&#9553;"c,
       .TopLeft = "&#9556;"c,
       .TopRight = "&#9559;"c,
       .BottomLeft = "&#9562;"c,
       .BottomRight = "&#9565;"c
   }
 
Dim result As String = DrawTextBox(input, verticalPadding, horizontalPadding, fillChar, drawingStyle)
 
Console.WriteLine(result)
IO.File.WriteAllText("\box.txt", result, Encoding.Unicode)
 

Salida:



UtilString.vb
Código
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 11-July-2023
' ***********************************************************************
 
#Region " Public Members Summary "
 
#Region " Functions "
 
' DrawTextBox(String, Opt: Integer, Opt: Integer, Opt: Char, Opt: BoxDrawingStyle) As String
 
#End Region
 
#End Region
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports System.Linq
Imports System.Text
 
#End Region
 
#Region " String Util "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Core.DataProcessing.Common
 
   Partial Public NotInheritable Class UtilString
 
#Region " Public Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Draws a box around the specified text, that is, a text-box.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim input As String = "Push this button!"
       ''' Dim verticalPadding As Integer = 1
       ''' Dim horizontalPadding As Integer = 2
       ''' Dim fillChar As Char = "&#9608;"c
       ''' Dim drawingStyle As New BoxDrawingStyle With {
       '''         .Top = "&#9552;"c, .Bottom = "&#9552;"c,
       '''         .Left = "&#9553;"c, .Right = "&#9553;"c,
       '''         .TopLeft = "&#9556;"c,
       '''         .TopRight = "&#9559;"c,
       '''         .BottomLeft = "&#9562;"c,
       '''         .BottomRight = "&#9565;"c
       '''     }
       '''
       ''' Dim result As String = DrawTextBox(input, verticalPadding, horizontalPadding, fillChar, drawingStyle)
       '''
       ''' Console.WriteLine(result)
       ''' IO.File.WriteAllText("\box.txt", result, Encoding.Unicode)
       ''' ' Output:
       ''' ' &#9556;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9559;
       ''' ' &#9553;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9553;
       ''' ' &#9553;&#9608;&#9608;Push this button!&#9608;&#9608;&#9553;
       ''' ' &#9553;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9553;
       ''' ' &#9562;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9552;&#9565;
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="input">
       ''' The input text to be boxed.
       ''' </param>
       '''
       ''' <param name="verticalPadding">
       ''' Optional. The number of vertical padding lines. Default value is: '0'.
       ''' </param>
       '''
       ''' <param name="horizontalPadding">
       ''' Optional. The number of horizontal padding characters. Default value is: '0'.
       ''' </param>
       '''
       ''' <param name="fillChar">
       ''' Optional. The character used to fill the empty space in the box. Default value is: " " (white-space).
       ''' </param>
       '''
       ''' <param name="drawingStyle">
       ''' Optional. The style of the box drawing. If not specified, a default style will be used.
       ''' <para></para>
       ''' If this value is null, "-" character is used for vertical sides,
       ''' "|" for horizontal sides and "+" for all corners.
       ''' <para></para>
       ''' Default value is: null.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' The resulting string containing the text enclosed in the box.
       ''' </returns>
       ''' --------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       Public Shared Function DrawTextBox(input As String,
                                          Optional verticalPadding As Integer = 0,
                                          Optional horizontalPadding As Integer = 0,
                                          Optional fillChar As Char = " "c,
                                          Optional drawingStyle As BoxDrawingStyle = Nothing) As String
 
 
           If String.IsNullOrEmpty(input) Then
               Throw New ArgumentNullException(paramName:=NameOf(input))
           End If
 
           If verticalPadding < 0 Then
               Throw New ArgumentException("Value can't be less than zero.", paramName:=NameOf(input))
           End If
 
           If horizontalPadding < 0 Then
               Throw New ArgumentException("Value can't be less than zero.", paramName:=NameOf(input))
           End If
 
           If fillChar.Equals(Nothing) Then
               Throw New ArgumentNullException(paramName:=NameOf(fillChar))
           End If
 
           If drawingStyle = BoxDrawingStyle.Empty Then
               drawingStyle = New BoxDrawingStyle With {
               .Top = "-"c, .Bottom = "-"c,
               .Left = "|"c, .Right = "|"c,
               .TopLeft = "+"c,
               .TopRight = "+"c,
               .BottomLeft = "+"c,
               .BottomRight = "+"c
           }
           End If
 
           Dim lines As String() = input.Split({Environment.NewLine}, StringSplitOptions.None)
           Dim linesLength As Integer = lines.Length
           Dim maxLength As Integer = lines.Max(Function(line As String) line.Length)
           Dim boxWidth As Integer = maxLength + (horizontalPadding * 2)
           Dim boxHeight As Integer = linesLength + (verticalPadding * 2)
 
           Dim sb As New StringBuilder()
 
           ' Draw top line.
           sb.AppendLine(drawingStyle.TopLeft & New String(drawingStyle.Top, boxWidth) & drawingStyle.TopRight)
 
           ' Draw top padding line(s).
           For i As Integer = 0 To verticalPadding - 1
               sb.AppendLine(drawingStyle.Left & New String(fillChar, boxWidth) & drawingStyle.Right)
           Next
 
           ' Draw inner line(s).
           For i As Integer = 0 To lines.Length - 1
               Dim paddedLine As String = lines(i).PadRight(maxLength, fillChar)
               sb.AppendLine(drawingStyle.Left & New String(fillChar, horizontalPadding) & paddedLine & New String(fillChar, horizontalPadding) & drawingStyle.Right)
           Next
 
           ' Draw bottom padding line(s).
           For i As Integer = 0 To verticalPadding - 1
               sb.AppendLine(drawingStyle.Left & New String(fillChar, boxWidth) & drawingStyle.Right)
           Next
 
           ' Draw bottom line.
           sb.AppendLine(drawingStyle.BottomLeft & New String(drawingStyle.Bottom, boxWidth) & drawingStyle.BottomRight)
           Return sb.ToString()
       End Function
 
#End Region
 
   End Class
 
End Namespace
 
#End Region
 


BoxDrawingStyle.vb
Código
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 11-July-2023
' ***********************************************************************
 
#Region " Option Statements "
 
Option Strict Off
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Usage Examples "
 
#End Region
 
#Region " Imports "
 
Imports System.Runtime.InteropServices
Imports System.Xml.Serialization
 
#End Region
 
#Region " BoxDrawingStyle "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Core.DataProcessing.Common
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Defines the characters used to draw the sides and corners of a box.
   ''' </summary>
   ''' --------------------------------------------------------------------------------------------------
   <Serializable>
   <XmlRoot(NameOf(BoxDrawingStyle))>
   <StructLayout(LayoutKind.Sequential)>
   Public Structure BoxDrawingStyle
 
#Region " Fields "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The character used for the top line of the box.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Top As Char
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The character used for the bottom line of the box.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Bottom As Char
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The character used for the left border of the box.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Left As Char
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The character used for the right border of the box.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Right As Char
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The character used for the top-left corner of the box.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public TopLeft As Char
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The character used for the top-right corner of the box.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public TopRight As Char
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The character used for the bottom-left corner of the box.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public BottomLeft As Char
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' The character used for the bottom-right corner of the box.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public BottomRight As Char
 
#End Region
 
#Region " Properties "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Gets a <see cref="BoxDrawingStyle"/> with all characters set to null.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       Public Shared ReadOnly Property Empty As BoxDrawingStyle
           Get
               Return New BoxDrawingStyle()
           End Get
       End Property
 
#End Region
 
#Region " Public Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Determines whether this instance of <see cref="BoxDrawingStyle"/> is equal to another object.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="obj">
       ''' The object to compare with this instance.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' <see langword="true"/> if the specified object is equal to this instance;
       ''' otherwise, <see langword="false"/>.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Overrides Function Equals(obj As Object) As Boolean
           If TypeOf obj Is BoxDrawingStyle Then
               Dim otherStyle As BoxDrawingStyle = DirectCast(obj, BoxDrawingStyle)
               Return Me.Top = otherStyle.Top AndAlso
                      Me.Bottom = otherStyle.Bottom AndAlso
                      Me.Left = otherStyle.Left AndAlso
                      Me.Right = otherStyle.Right AndAlso
                      Me.TopLeft = otherStyle.TopLeft AndAlso
                      Me.TopRight = otherStyle.TopRight AndAlso
                      Me.BottomLeft = otherStyle.BottomLeft AndAlso
                      Me.BottomRight = otherStyle.BottomRight
           End If
           Return False
       End Function
 
#End Region
 
#Region " Operators "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Determines whether two instances of <see cref="BoxDrawingStyle"/> are equal.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="style1">
       ''' The first <see cref="BoxDrawingStyle"/> to compare.
       ''' </param>
       '''
       ''' <param name="style2">
       ''' The second <see cref="BoxDrawingStyle"/> to compare.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' <see langword="true"/> if the specified instances are equal; otherwise, <see langword="false"/>.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Shared Operator =(style1 As BoxDrawingStyle, style2 As BoxDrawingStyle) As Boolean
           Return style1.Top = style2.Top AndAlso
                      style1.Bottom = style2.Bottom AndAlso
                      style1.Left = style2.Left AndAlso
                      style1.Right = style2.Right AndAlso
                      style1.TopLeft = style2.TopLeft AndAlso
                      style1.TopRight = style2.TopRight AndAlso
                      style1.BottomLeft = style2.BottomLeft AndAlso
                      style1.BottomRight = style2.BottomRight
       End Operator
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Determines whether two instances of <see cref="BoxDrawingStyle"/> are not equal.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="style1">
       ''' The first <see cref="BoxDrawingStyle"/> to compare.
       ''' </param>
       '''
       ''' <param name="style2">
       ''' The second <see cref="BoxDrawingStyle"/> to compare.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' <see langword="true"/> if the specified instances are not equal; otherwise, <see langword="false"/>.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       Public Shared Operator <>(style1 As BoxDrawingStyle, style2 As BoxDrawingStyle) As Boolean
           Return Not (style1 = style2)
       End Operator
 
#End Region
 
   End Structure
 
End Namespace
 
#End Region
 

Elektro Enjuto:
Algunos atajos a modo de extensiones de métodos para simplificar la generación de excepciones al cumplir cierta condición en un objeto.

Ejemplos de uso:

- Object.ThrowIf
Código
Dim value As Integer = 0
' value.ThrowIf(Of ArgumentOutOfRangeException)(Function(x) x = 0)
value.ThrowIf(Function(x) x = 0, New ArgumentOutOfRangeException(paramName:=NameOf(value)))

- Object.ThrowIfNotInRange
Código
Dim value As Integer = 10
' value.ThrowIfNotInRange(min:=1, max:=9)
value.ThrowIfNotInRange(min:=1, max:=9, message:="Value is not within the allowed range.", paramName:=NameOf(value))

- Object.ThrowIfNull
Código
Dim obj As Object = Nothing
' obj.ThrowIfNull(Of ArgumentNullException)
obj.ThrowIfNull(New ArgumentNullException(paramName:=NameOf(obj)))

- Object.ThrowIfDefault
Código
Dim obj As Integer = 0
' obj.ThrowIfDefault(Of ArgumentNullException)
obj.ThrowIfDefault(New ArgumentNullException(paramName:=NameOf(obj)))


Y para un valor booleano:

- Boolean.ThrowIfFalse
Código
Dim value As Boolean = False
' value.ThrowIfFalse(Of ArgumentException)
value.ThrowIfFalse(New ArgumentException(message:="'true' expected.", paramName:=NameOf(value)))

- Boolean.ThrowIfTrue
Código
Dim value As Boolean = True
' value.ThrowIfTrue(Of ArgumentException)
value.ThrowIfTrue(New ArgumentException(message:="'false' expected.", paramName:=NameOf(value)))


ObjectExtensions.vb
Código
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 09-July-2023
' ***********************************************************************
 
#Region " Public Members Summary "
 
' Object.ThrowIf(Of TObject, TException As Exception)(Func(Of TObject, Boolean), Opt: TException)
' Object.ThrowIfNull(Of TException As Exception)(Opt: TException)
' Object.ThrowIfDefault(Of TException As Exception)(Opt: TException)
' Object.ThrowIfNotInRange(T, T, Opt: String, Opt: String)
 
' Object.IsDefault As Boolean
 
#End Region
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports System.ComponentModel
Imports System.Reflection
Imports System.Runtime.CompilerServices
 
#End Region
 
#Region " Object Extensions "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Extensions.ObjectExtensions
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Contains custom extension methods to use with the <see cref="Object"/> type.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   <ImmutableObject(True)>
   <HideModuleName>
   Public Module ObjectExtensions
 
#Region " Public Extension Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Throws the specified exception if the given condition in the source object is true.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim value As Integer = 0
       ''' ' value.ThrowIf(Of ArgumentOutOfRangeException)(Function(x) x = 0)
       ''' value.ThrowIf(Function(x) x = 0, New ArgumentOutOfRangeException(paramName:=NameOf(value)))
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <typeparam name="TObject">
       ''' The type of object to evaluate.
       ''' </typeparam>
       '''
       ''' <typeparam name="TException">
       ''' The type of exception to throw.
       ''' </typeparam>
       '''
       ''' <param name="obj">
       ''' The object to evaluate.
       ''' </param>
       '''
       ''' <param name="predicate">
       ''' The predicate function to evaluate the object.
       ''' </param>
       '''
       ''' <param name="ex">
       ''' Optionally, a instance of the exception to throw when
       ''' the <paramref name="predicate"/> condition is true.
       ''' <para></para>
       ''' If this value is null, a default instance of the exception type will be used.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Sub ThrowIf(Of TObject, TException As Exception)(obj As TObject,
                                                               predicate As Func(Of TObject, Boolean),
                                                               Optional ex As TException = Nothing)
 
           If predicate(obj) Then
               If ex Is Nothing Then
                   ex = Activator.CreateInstance(Of TException)
               End If
               Throw ex
           End If
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Throws the specified exception if the source object is null.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim obj As Object = Nothing
       ''' ' obj.ThrowIfNull(Of ArgumentNullException)
       ''' obj.ThrowIfNull(New ArgumentNullException(paramName:=NameOf(obj)))
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <typeparam name="TException">
       ''' The type of exception to throw.
       ''' </typeparam>
       '''
       ''' <param name="obj">
       ''' The object to check for null.
       ''' </param>
       '''
       ''' <param name="ex">
       ''' Optionally, a instance of the exception to throw when the source object is null.
       ''' <para></para>
       ''' If this value is null, a default instance of the exception type will be used.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Sub ThrowIfNull(Of TException As Exception)(obj As Object, Optional ex As TException = Nothing)
 
           If obj Is Nothing Then
               If ex Is Nothing Then
                   ex = Activator.CreateInstance(Of TException)
               End If
               Throw ex
           End If
 
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Throws the specified exception if the source object is the default value of its type.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim obj As Integer = 0
       ''' ' obj.ThrowIfDefault(Of ArgumentNullException)
       ''' obj.ThrowIfDefault(New ArgumentNullException(paramName:=NameOf(obj)))
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <typeparam name="TException">
       ''' The type of exception to throw.
       ''' </typeparam>
       '''
       ''' <param name="obj">
       ''' The object to evaluate.
       ''' </param>
       '''
       ''' <param name="ex">
       ''' Optionally, a instance of the exception to throw when the source object is the default value of its type.
       ''' <para></para>
       ''' If this value is null, a default instance of the exception type will be used.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Sub ThrowIfDefault(Of TObject, TException As Exception)(obj As TObject, Optional ex As TException = Nothing)
           If obj.IsDefault() Then
               If ex Is Nothing Then
                   ex = Activator.CreateInstance(Of TException)
               End If
               Throw ex
           End If
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Throws an <see cref="ArgumentOutOfRangeException"/> if the
       ''' source value is not within the specified range.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim value As Integer = 10
       ''' ' value.ThrowIfNotInRange(min:=1, max:=9)
       ''' value.ThrowIfNotInRange(min:=1, max:=9, message:="Value is not within the allowed range.", paramName:=NameOf(value))
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <typeparam name="T">
       ''' The type of value to evaluate.
       ''' </typeparam>
       '''
       ''' <param name="value">
       ''' The value to evaluate.
       ''' </param>
       '''
       ''' <param name="min">
       ''' The minimum allowed value (inclusive).
       ''' </param>
       '''
       ''' <param name="max">
       ''' The maximum allowed value (inclusive).
       ''' </param>
       '''
       ''' <param name="message">
       ''' Optionally, the custom error message for the <see cref="ArgumentOutOfRangeException"/>.
       ''' </param>
       '''
       ''' <param name="paramName">
       ''' Optionally, the name of the parameter that caused the <see cref="ArgumentOutOfRangeException"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <exception cref="ArgumentOutOfRangeException">
       ''' Thrown when the value is not within the specified range.
       ''' </exception>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Sub ThrowIfNotInRange(Of T As {IComparable(Of T), IConvertible, IEquatable(Of T), IFormattable})(value As T, min As T, max As T,
                                                                                                               Optional message As String = Nothing,
                                                                                                               Optional paramName As String = Nothing)
 
           If value.CompareTo(min) < 0 OrElse value.CompareTo(max) > 0 Then
#Disable Warning CA2208 ' Instantiate argument exceptions correctly
               Dim ex As New ArgumentOutOfRangeException()
#Enable Warning CA2208 ' Instantiate argument exceptions correctly
               Dim messageField As FieldInfo = Nothing
               Dim actualValueField As FieldInfo = Nothing
               Dim paramNameField As FieldInfo = Nothing
               Dim bindingFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.NonPublic
 
               Dim exType As Type = ex.GetType()
               If actualValueField Is Nothing Then
                   actualValueField = exType.GetField("m_actualValue", bindingFlags)
               End If
 
               Do While exType IsNot Nothing AndAlso
                       ((message IsNot Nothing AndAlso messageField Is Nothing) OrElse
                        (paramName IsNot Nothing AndAlso paramNameField Is Nothing))
 
                   If actualValueField Is Nothing Then
                       actualValueField = exType.GetField("m_actualValue", bindingFlags)
                   End If
 
                   If message IsNot Nothing AndAlso messageField Is Nothing Then
                       messageField = exType.GetField("_message", bindingFlags)
                   End If
 
                   If paramName IsNot Nothing AndAlso paramNameField Is Nothing Then
                       paramNameField = exType.GetField("m_paramName", bindingFlags)
                   End If
 
                   exType = exType.BaseType
               Loop
 
               actualValueField?.SetValue(ex, value)
               messageField?.SetValue(ex, message)
               paramNameField?.SetValue(ex, paramName)
               Throw ex
           End If
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Determines whether the source object is the default value of its type.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <typeparam name="T">
       ''' The type of the objectto evaluate.
       ''' </typeparam>
       '''
       ''' <param name="obj">
       ''' The object to evaluate.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' Returns True if the source object is the default value of its type; otherwise, False.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Function IsDefault(Of T)(obj As T) As Boolean
           Return EqualityComparer(Of T).Default.Equals(obj, Nothing)
       End Function
 
#End Region
 
   End Module
 
End Namespace
 
#End Region
 



BooleanExtensions.vb
Código
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 09-July-2023
' ***********************************************************************
 
#Region " Public Members Summary "
 
' Boolean.ThrowIfTrue(Of TException As Exception)(Opt: TException)
' Boolean.ThrowIfFalse(Of TException As Exception)(Opt: TException)
 
#End Region
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports System.ComponentModel
Imports System.Runtime.CompilerServices
 
#End Region
 
#Region " Boolean Extensions "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Extensions.BooleanExtensions
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Contains custom extension methods to use with <see cref="Boolean"/> datatype.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   <HideModuleName>
   Public Module BooleanExtensions
 
#Region " Public Extension Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Throws an exception if the source value is true.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim value As Boolean = True
       ''' ' value.ThrowIfTrue(Of ArgumentException)
       ''' value.ThrowIfTrue(New ArgumentException(message:="'false' expected.", paramName:=NameOf(value)))
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------        '''
       ''' <typeparam name="TException">
       ''' The type of exception to throw.
       ''' </typeparam>
       '''
       ''' <param name="value">
       ''' The value to evaluate.
       ''' </param>
       '''
       ''' <param name="ex">
       ''' Optionally, a instance of the exception to throw if the source <paramref name="value"/> is true.
       ''' <para></para>
       ''' If this value is null, a default instance of the exception type will be used.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Sub ThrowIfTrue(Of TException As Exception)(value As Boolean, Optional ex As TException = Nothing)
 
           If value Then
               If ex Is Nothing Then
                   ex = Activator.CreateInstance(Of TException)
               End If
               Throw ex
           End If
 
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Throws an exception if the source value is false.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim value As Boolean = False
       ''' ' value.ThrowIfFalse(Of ArgumentException)
       ''' value.ThrowIfFalse(New ArgumentException(message:="'true' expected.", paramName:=NameOf(value)))
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------        '''
       ''' <typeparam name="TException">
       ''' The type of exception to throw.
       ''' </typeparam>
       '''
       ''' <param name="value">
       ''' The value to evaluate.
       ''' </param>
       '''
       ''' <param name="ex">
       ''' Optionally, a instance of the exception to throw if the source <paramref name="value"/> is false.
       ''' <para></para>
       ''' If this value is null, a default instance of the exception type will be used.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Sub ThrowIfFalse(Of TException As Exception)(value As Boolean, Optional ex As TException = Nothing)
 
           If Not value Then
               If ex Is Nothing Then
                   ex = Activator.CreateInstance(Of TException)
               End If
               Throw ex
           End If
 
       End Sub
 
#End Region
 
   End Module
 
End Namespace
 
#End Region
 

Elektro Enjuto:
Un código para forzar la eliminación de un directorio (que tenga el atributo de 'solo lectura') y sus subdirectorios.

Y también para forzar la eliminación o el reciclado de un archivo (que tenga el atributo de 'solo lectura').

Nota: este código no modifica los permisos de usuario de archivos ni de carpetas.


DirectoryInfoExtensions.vb
Código
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 09-July-2023
' ***********************************************************************
 
#Region " Public Members Summary "
 
' DirectoryInfo.ForceDelete()
' DirectoryInfo.ForceDelete(Boolean)
 
#End Region
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports System.ComponentModel
Imports System.IO
Imports System.Runtime.CompilerServices
Imports System.Security
 
Imports DevCase.Win32
 
#End Region
 
#Region " DirectoryInfo Extensions "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Extensions.DirectoryInfoExtensions
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Contains custom extension methods to use with <see cref="Global.System.IO.DirectoryInfo"/> type.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   <HideModuleName>
   Public Module DirectoryInfoExtensions
 
#Region " Public Extension Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Forces the deletion of the specified directory if it is empty,
       ''' by removing the read-only attribute and deleting it.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="directory">
       ''' The directory to be deleted.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Sub ForceDelete(directory As DirectoryInfo)
 
           If directory.IsRootVolume Then
               Throw New InvalidOperationException($"An attempt to delete the root directory of a volume (""{directory.FullName}"").")
           End If
 
           If directory.IsReadOnly Then
               directory.Attributes = directory.Attributes And Not FileAttributes.ReadOnly
           End If
 
           directory.Delete(recursive:=False)
 
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Forces the deletion of the specified directory, specifying whether to delete subdirectories and files
       ''' by removing the read-only attribute and deleting them.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="directory">
       ''' The directory to be deleted.
       ''' </param>
       '''
       ''' <param name="recursive">
       ''' True to delete this directory, its subdirectories, and all files; otherwise, False.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       <SecuritySafeCritical>
       Public Sub ForceDelete(directory As DirectoryInfo, recursive As Boolean)
 
           If directory.IsRootVolume Then
               Throw New InvalidOperationException($"An attempt to delete the root directory of a volume (""{directory.FullName}"").")
           End If
 
           If Not recursive AndAlso Not directory.IsEmpty Then
               ' recursive value is False and the user is attempting to delete
               ' a directory that is not empty (it needs recursive deletion).
               '
               ' We let the built-in "Delete" method to throw the exception for us.
               IO.Directory.Delete(directory.FullName, recursive:=False)
           End If
 
           If directory.IsReadOnly Then
               directory.Attributes = directory.Attributes And Not FileAttributes.ReadOnly
           End If
 
           ' Try recursive deletion.
           Try
               For Each subdirectory As DirectoryInfo In directory.GetDirectories("*", SearchOption.AllDirectories)
                   If subdirectory.IsReadOnly Then
                       subdirectory.Attributes = subdirectory.Attributes And Not FileAttributes.ReadOnly
                   End If
               Next
               For Each file As FileInfo In directory.GetFiles("*", SearchOption.AllDirectories)
                   If file.IsReadOnly Then
                       file.Attributes = file.Attributes And Not FileAttributes.ReadOnly
                   End If
               Next
               directory.Delete(recursive:=True)
 
           Catch ex As Exception
               Throw
 
           End Try
 
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Determines whether the source directory is read-only,
       ''' i.e., it has the <see cref="FileAttributes.ReadOnly"/> attribute.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="directory">
       ''' The directory to check.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' True if the directory is read-only; otherwise, False.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Function IsReadOnly(directory As DirectoryInfo) As Boolean
           Return (directory.Attributes And FileAttributes.ReadOnly) <> 0
       End Function
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Determines whether the <see cref="DirectoryInfo.FullName"/> path
       ''' in the source directory refers to the root of a volume (e.g "C:\").
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="directory">
       ''' The directory to check.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' True if the <see cref="DirectoryInfo.FullName"/> path
       ''' in the source directory refers to the root of a volume (e.g "C:\");
       ''' otherwise, False.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Function IsRootVolume(directory As DirectoryInfo) As Boolean
           Return NativeMethods.PathCchIsRoot(directory.FullName)
       End Function
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Determines whether the source directory is empty (contains no files and no directories).
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="sender">
       ''' The source <see cref="Global.System.IO.DirectoryInfo"/>.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' <see langword="True"/> if the directory is empty (contains no files and no directories),
       ''' otherwise, <see langword="False"/>.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       Public Function IsEmpty(sender As Global.System.IO.DirectoryInfo) As Boolean
 
           Return Not sender.EnumerateFileSystemInfos().Any()
 
       End Function
 
#End Region
 
   End Module
 
End Namespace
 
#End Region
 


KernelBase.vb
Código
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 01-July-2019
' ***********************************************************************
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports System.Runtime.InteropServices
Imports System.Security
 
#End Region
 
#Region " P/Invoking "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Win32.NativeMethods
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Platform Invocation methods (P/Invoke), access unmanaged code.
   ''' <para></para>
   ''' KernelBase.dll.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   <HideModuleName>
   <SuppressUnmanagedCodeSecurity>
   <CodeAnalysis.SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification:="Required to migrate this code to .NET Core")>
   <CodeAnalysis.SuppressMessage("Interoperability", "CA1401:P/Invokes should not be visible", Justification:="")>
   Public Module KernelBase
 
#Region " KernelBase.dll "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Determines whether a path string refers to the root of a volume.
       ''' <para></para>
       ''' This function differs from <see cref="NativeMethods.PathIsRoot"/> in that it accepts paths with "\", "\?" and "\?\UNC" prefixes.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <remarks>
       ''' <see href="https://docs.microsoft.com/en-us/windows/desktop/api/pathcch/nf-pathcch-pathcchisroot"/>
       ''' </remarks>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="path">
       ''' A pointer to the path string.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <returns>
       ''' Returns <see langword="True"/> if the specified path is a root, or <see langword="False"/> otherwise.
       ''' </returns>
       ''' ----------------------------------------------------------------------------------------------------
       <DllImport("KernelBase.dll", SetLastError:=True, CharSet:=CharSet.Auto, BestFitMapping:=False, ThrowOnUnmappableChar:=True)>
       Public Function PathCchIsRoot(path As String
       ) As <MarshalAs(UnmanagedType.Bool)> Boolean
       End Function
 
#End Region
 
   End Module
 
End Namespace
 
#End Region
 


FileInfoExtensions.vb
Código
' ***********************************************************************
' Author   : ElektroStudios
' Modified : 10-September-2023
' ***********************************************************************
 
#Region " Public Members Summary "
 
' FileInfo.ForceDelete()
' FileInfo.ForceRecycle(UIOption)
 
#End Region
 
#Region " Option Statements "
 
Option Strict On
Option Explicit On
Option Infer Off
 
#End Region
 
#Region " Imports "
 
Imports System.ComponentModel
Imports System.IO
Imports System.Runtime.CompilerServices
Imports System.Security
 
#End Region
 
#Region " FileInfo Extensions "
 
' ReSharper disable once CheckNamespace
 
Namespace DevCase.Extensions.FileInfoExtensions
 
   ''' ----------------------------------------------------------------------------------------------------
   ''' <summary>
   ''' Contains custom extension methods to use with <see cref="Global.System.IO.FileInfo"/> type.
   ''' </summary>
   ''' ----------------------------------------------------------------------------------------------------
   <HideModuleName>
   Public Module FileInfoExtensions
 
#Region " Public Extension Methods "
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Sends the source file to the Recycle Bin.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <example> This is a code example.
       ''' <code language="VB.NET">
       ''' Dim file As New FileInfo("C:\File.ext")
       ''' file.Recycle(UIOption.OnlyErrorDialogs)
       ''' </code>
       ''' </example>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="sender">
       ''' The source <see cref="Global.System.IO.FileInfo"/>.
       ''' </param>
       '''
       ''' <param name="dialog">
       ''' Specifies which dialog boxes to show when recycling.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       <SecuritySafeCritical>
       Public Sub Recycle(sender As Global.System.IO.FileInfo, dialog As FileIO.UIOption)
 
           Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(sender.FullName, dialog, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
 
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Forces the permanent deletion of the specified file by removing the read-only attribute and deleting it.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="file">
       ''' The file to be permanently deleted.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       <SecuritySafeCritical>
       Public Sub ForceDelete(file As FileInfo)
 
           If file.IsReadOnly Then
               file.Attributes = file.Attributes And Not FileAttributes.ReadOnly
           End If
 
           file.Delete()
 
       End Sub
 
       ''' ----------------------------------------------------------------------------------------------------
       ''' <summary>
       ''' Forces the recycling of the specified file by removing the read-only attribute and sending it to the recycle bin.
       ''' </summary>
       ''' ----------------------------------------------------------------------------------------------------
       ''' <param name="file">
       ''' The file to be permanently deleted.
       ''' </param>
       ''' ----------------------------------------------------------------------------------------------------
       <DebuggerStepThrough>
       <Extension>
       <EditorBrowsable(EditorBrowsableState.Always)>
       <SecuritySafeCritical>
       Public Sub ForceRecycle(file As FileInfo, dialog As FileIO.UIOption)
 
           If file.IsReadOnly Then
               file.Attributes = file.Attributes And Not FileAttributes.ReadOnly
           End If
 
           file.Recycle(dialog)
 
       End Sub
 
#End Region
 
   End Module
 
End Namespace
 
#End Region
 

Navegación

[0] Índice de Mensajes

[#] Página Siguiente

[*] Página Anterior