elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [APORTE] FileDater (Preserva, establece, o restaura las fechas de un archivo)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [APORTE] FileDater (Preserva, establece, o restaura las fechas de un archivo)  (Leído 1,418 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.818



Ver Perfil
[APORTE] FileDater (Preserva, establece, o restaura las fechas de un archivo)
« en: 22 Julio 2014, 05:34 am »

Esta Class sirve para preservar una o todas las fechas de un archivo para poder restaurarlas en cualquier otro momento, me parece muy útil para modificar archivos los cuales no quieres que sus fechas actuales se alteren después de la modificación... y con este "ayudante" ahorrarás tiempo y escritura de código.
Esta Class también sirve para establecer fechas en un archivo (aunque esa característica simplemente está ahí para decorar, para extender un poco su funcionalidad).

Nota: En la Class podrán notar que le añadí la implementación de la interface IDisposable, en un principio esto podría parecer innecesario, pero la añadí para evitar el poder crear instancias que usen el mismo archivo, ya que no le encuentro sentido alguno al permitir estar preservando/restaurando las fechas de un mismo archivo en distintas instancias y esto podría ocasionar confusiones además de un uso indebido, y además, de esta forma el uso de los bloques Using también pueden prevenir algún que otro descuido.

Espero que a alguien le sirva :).





Ejemplo de uso:

1.
Código
  1.        ' Instance the FileDater Class.
  2.        Using fd As New FileDater(File:="C:\Test File.txt")
  3.  
  4.            ' Preserve the current date-modified of the file.
  5.            fd.Preserve(FileDater.DateType.Modified)
  6.  
  7.            ' Do some kind of operation that alters the current date-modified of the file.
  8.            IO.File.AppendAllText(fd.File.FullName, New String("X"c, 10I))
  9.  
  10.            ' Restore the previously preserved date-modified on the TestFile.
  11.            fd.Restore(FileDater.DateType.Modified)
  12.  
  13.        End Using '/ fd

2.
Código
  1.        ' Instance a test FileInfo using an unique temp file.
  2.        Dim TestFile As New IO.FileInfo(IO.Path.GetTempFileName)
  3.  
  4.        ' Instance the FileDater Class.
  5.        Using fd As New FileDater(File:=TestFile)
  6.  
  7.            ' Preserve the current dates of the TestFile.
  8.            fd.Preserve(FileDater.DateType.Created Or FileDater.DateType.Accessed Or FileDater.DateType.Modified)
  9.  
  10.            ' Show the type of the current preserved dates.
  11.            MessageBox.Show(fd.PreservedTypes.ToString)
  12.  
  13.            ' Show current preserved date-creation.
  14.            MessageBox.Show(fd.PreservedCreationDate.ToString)
  15.  
  16.            ' Modify the current date-creation on the TestFile.
  17.            fd.Set(FileDater.DateType.Created, Date.Parse("01/01/2015"))
  18.  
  19.            ' Restore the previously preserved date-creation on the TestFile.
  20.            fd.Restore(FileDater.DateType.Created)
  21.  
  22.            ' Show the current Creation date of the TestFile.
  23.            MessageBox.Show(TestFile.CreationTime)
  24.  
  25.        End Using





El código:

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 07-22-2014
  4. ' ***********************************************************************
  5. ' <copyright file="FileDater.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10. #Region " Usage Examples "
  11.  
  12. #Region " Example 1 "
  13.  
  14. '' Instance the FileDater Class.
  15. 'Using fd As New FileDater(File:="C:\Test File.txt")
  16.  
  17. '    ' Preserve the current date-modified of the file.
  18. '    fd.Preserve(FileDater.DateType.Modified)
  19.  
  20. '    ' Do some kind of operation that alters the current date-modified of the file.
  21. '    IO.File.AppendAllText(fd.File.FullName, New String("X"c, 10I))
  22.  
  23. '    ' Restore the previously preserved date-modified on the TestFile.
  24. '    fd.Restore(FileDater.DateType.Modified)
  25.  
  26. 'End Using '/ fd
  27.  
  28. #End Region
  29.  
  30. #Region " Example 2 "
  31.  
  32. '' Instance a test FileInfo using an unique temp file.
  33. 'Dim TestFile As New IO.FileInfo(IO.Path.GetTempFileName)
  34.  
  35. '' Instance the FileDater Class.
  36. 'Using fd As New FileDater(File:=TestFile)
  37.  
  38. '    ' Preserve the current dates of the TestFile.
  39. '    fd.Preserve(FileDater.DateType.Created Or FileDater.DateType.Accessed Or FileDater.DateType.Modified)
  40.  
  41. '    ' Show the type of the current preserved dates.
  42. '    MessageBox.Show(fd.PreservedTypes.ToString)
  43.  
  44. '    ' Show current preserved date-creation.
  45. '    MessageBox.Show(fd.PreservedCreationDate.ToString)
  46.  
  47. '    ' Modify the current date-creation on the TestFile.
  48. '    fd.Set(FileDater.DateType.Created, Date.Parse("01/01/2015"))
  49.  
  50. '    ' Restore the previously preserved date-creation on the TestFile.
  51. '    fd.Restore(FileDater.DateType.Created)
  52.  
  53. '    ' Show the current Creation date of the TestFile.
  54. '    MessageBox.Show(TestFile.CreationTime)
  55.  
  56. 'End Using
  57.  
  58. #End Region
  59.  
  60. #End Region
  61.  
  62. #Region " Imports "
  63.  
  64. Imports System.ComponentModel
  65. Imports System.IO
  66.  
  67. #End Region
  68.  
  69. #Region " FileDater "
  70.  
  71. ''' <summary>
  72. ''' Contains methods to preserve, set, and restore the dates contained on file.
  73. ''' </summary>
  74. Public NotInheritable Class FileDater : Implements IDisposable
  75.  
  76. #Region " Objects "
  77.  
  78.    ''' <summary>
  79.    ''' Contains the files that are already used in the constructor to prevent a duplicated instance for the same file.
  80.    ''' </summary>
  81.    Private Shared InstancedFiles As New List(Of FileInfo)
  82.  
  83. #End Region
  84.  
  85. #Region " Properties "
  86.  
  87.    ''' <summary>
  88.    ''' Gets the file.
  89.    ''' </summary>
  90.    ''' <value>The file.</value>
  91.    Public ReadOnly Property [File] As FileInfo
  92.        Get
  93.            Return Me._File
  94.        End Get
  95.    End Property
  96.    Private _File As FileInfo
  97.  
  98.    ''' <summary>
  99.    ''' Gets the type of the current preserved dates.
  100.    ''' </summary>
  101.    Public ReadOnly Property PreservedTypes As DateType
  102.        Get
  103.            Return Me._PreservedTypes
  104.        End Get
  105.    End Property
  106.    Private _PreservedTypes As DateType = Nothing
  107.  
  108.    ''' <summary>
  109.    ''' Gets the preserved creation date.
  110.    ''' </summary>
  111.    ''' <value>The preserved creation date.</value>
  112.    Public ReadOnly Property PreservedCreationDate As Date
  113.        Get
  114.            Return Me._PreservedCreationDate
  115.        End Get
  116.    End Property
  117.    Private _PreservedCreationDate As Date
  118.  
  119.    ''' <summary>
  120.    ''' Gets the preserved last-access date.
  121.    ''' </summary>
  122.    ''' <value>The preserved creation date.</value>
  123.    Public ReadOnly Property PreservedLastAccessDate As Date
  124.        Get
  125.            Return Me._PreservedLastAccessDate
  126.        End Get
  127.    End Property
  128.    Private _PreservedLastAccessDate As Date
  129.  
  130.    ''' <summary>
  131.    ''' Gets the preserved last-modify date.
  132.    ''' </summary>
  133.    ''' <value>The preserved creation date.</value>
  134.    Public ReadOnly Property PreservedLastModifyDate As Date
  135.        Get
  136.            Return Me._PreservedLastModifyDate
  137.        End Get
  138.    End Property
  139.    Private _PreservedLastModifyDate As Date
  140.  
  141. #End Region
  142.  
  143. #Region " Enumerations "
  144.  
  145.    ''' <summary>
  146.    ''' Contains a FileDate flag.
  147.    ''' </summary>
  148.    <FlagsAttribute>
  149.    Public Enum DateType As Integer
  150.  
  151.        ''' <summary>
  152.        ''' The date when the file was created.
  153.        ''' </summary>
  154.        Created = 1I
  155.  
  156.        ''' <summary>
  157.        ''' The date when the file was accessed by last time.
  158.        ''' </summary>
  159.        Accessed = 2I
  160.  
  161.        ''' <summary>
  162.        ''' The date when the file was modified by last time.
  163.        ''' </summary>
  164.        Modified = 4I
  165.  
  166.    End Enum
  167.  
  168. #End Region
  169.  
  170. #Region " Constructors "
  171.  
  172.    ''' <summary>
  173.    ''' Initializes a new instance of the <see cref="FileDater"/> class.
  174.    ''' </summary>
  175.    ''' <param name="File">Indicates the <see cref="FileInfo"/> instance.</param>
  176.    ''' <exception cref="System.Exception"></exception>
  177.    Public Sub New(ByVal [File] As FileInfo)
  178.  
  179.        If Not InstancedFiles.Contains([File]) Then
  180.            Me._File = [File]
  181.            InstancedFiles.Add([File])
  182.  
  183.        Else
  184.            Throw New Exception(String.Format("Another instance of the '{0}' class is using the same file.", MyBase.GetType.Name))
  185.  
  186.        End If
  187.  
  188.    End Sub
  189.  
  190.    ''' <summary>
  191.    ''' Initializes a new instance of the <see cref="FileDater"/> class.
  192.    ''' </summary>
  193.    ''' <param name="File">Indicates the file.</param>
  194.    Public Sub New(ByVal [File] As String)
  195.        Me.New(New FileInfo([File]))
  196.    End Sub
  197.  
  198.    ''' <summary>
  199.    ''' Prevents a default instance of the <see cref="FileDater"/> class from being created.
  200.    ''' </summary>
  201.    Private Sub New()
  202.    End Sub
  203.  
  204. #End Region
  205.  
  206. #Region " Hidden Methods "
  207.  
  208.    ''' <summary>
  209.    ''' Serves as a hash function for a particular type.
  210.    ''' </summary>
  211.    <EditorBrowsable(EditorBrowsableState.Never)>
  212.    Public Shadows Sub GetHashCode()
  213.    End Sub
  214.  
  215.    ''' <summary>
  216.    ''' Determines whether the specified System.Object instances are considered equal.
  217.    ''' </summary>
  218.    <EditorBrowsable(EditorBrowsableState.Never)>
  219.    Public Shadows Sub Equals()
  220.    End Sub
  221.  
  222.    ''' <summary>
  223.    ''' Determines whether the specified System.Object instances are the same instance.
  224.    ''' </summary>
  225.    <EditorBrowsable(EditorBrowsableState.Never)>
  226.    Private Shadows Sub ReferenceEquals()
  227.    End Sub
  228.  
  229.    ''' <summary>
  230.    ''' Returns a String that represents the current object.
  231.    ''' </summary>
  232.    <EditorBrowsable(EditorBrowsableState.Never)>
  233.    Public Shadows Sub ToString()
  234.    End Sub
  235.  
  236. #End Region
  237.  
  238. #Region " Public Methods "
  239.  
  240.    ''' <summary>
  241.    ''' Preserves the specified dates of the file to restore them later at any time.
  242.    ''' Note: Dates can be preserved again at any time.
  243.    ''' </summary>
  244.    ''' <param name="DateType">Indicates the type of dates to preserve.</param>
  245.    Public Sub Preserve(ByVal DateType As DateType)
  246.  
  247.        Me.DisposedCheck()
  248.  
  249.        ' Creation
  250.        If DateType.HasFlag(FileDater.DateType.Created) Then
  251.            Me._PreservedCreationDate = Me._File.CreationTime
  252.        End If
  253.  
  254.        ' Accessed
  255.        If DateType.HasFlag(FileDater.DateType.Accessed) Then
  256.            Me._PreservedLastAccessDate = Me._File.LastAccessTime
  257.        End If
  258.  
  259.        ' Modified
  260.        If DateType.HasFlag(FileDater.DateType.Modified) Then
  261.            Me._PreservedLastModifyDate = Me._File.LastWriteTime
  262.        End If
  263.  
  264.        Me._PreservedTypes = DateType
  265.  
  266.    End Sub
  267.  
  268.    ''' <summary>
  269.    ''' Preserves at once all the dates of the file to restore them later at any time.
  270.    ''' Note: Dates can be preserved again at any time.
  271.    ''' </summary>
  272.    Public Sub Preserve()
  273.  
  274.        Me.DisposedCheck()
  275.  
  276.        Me._PreservedCreationDate = Me._File.CreationTime
  277.        Me._PreservedLastAccessDate = Me._File.LastAccessTime
  278.        Me._PreservedLastModifyDate = Me._File.LastWriteTime
  279.  
  280.        Me._PreservedTypes = DateType.Created Or DateType.Accessed Or DateType.Modified
  281.  
  282.    End Sub
  283.  
  284.    ''' <summary>
  285.    ''' Restores the specified preserved dates on the file.
  286.    ''' Note: Calling this method does not cause the deletion of any preserved date.
  287.    ''' </summary>
  288.    ''' <param name="DateType">Indicates the type of dates to restore on the file.</param>
  289.    ''' <exception cref="System.Exception">Any date was preserved.</exception>
  290.    Public Sub Restore(ByVal DateType As DateType)
  291.  
  292.        Me.DisposedCheck()
  293.  
  294.        ' Creation
  295.        If DateType.HasFlag(FileDater.DateType.Created) _
  296.        AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then
  297.  
  298.            Me._File.CreationTime = Me._PreservedCreationDate
  299.  
  300.        ElseIf DateType.HasFlag(FileDater.DateType.Created) _
  301.        AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then
  302.  
  303.            Throw New Exception(String.Format("The specified date was not preserved.")) With {
  304.                .Source = FileDater.DateType.Created.ToString
  305.            }
  306.  
  307.        End If
  308.  
  309.        ' Accessed
  310.        If DateType.HasFlag(FileDater.DateType.Accessed) _
  311.        AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then
  312.  
  313.            Me._File.LastAccessTime = Me._PreservedLastAccessDate
  314.  
  315.        ElseIf DateType.HasFlag(FileDater.DateType.Accessed) _
  316.        AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then
  317.  
  318.            Throw New Exception(String.Format("The specified date was not preserved.")) With {
  319.                .Source = FileDater.DateType.Accessed.ToString
  320.            }
  321.  
  322.        End If
  323.  
  324.        ' Modified
  325.        If DateType.HasFlag(FileDater.DateType.Modified) _
  326.        AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then
  327.  
  328.            Me._File.LastWriteTime = Me._PreservedLastModifyDate
  329.  
  330.        ElseIf DateType.HasFlag(FileDater.DateType.Modified) _
  331.        AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then
  332.  
  333.            Throw New Exception(String.Format("The specified date was not preserved.")) With {
  334.                .Source = FileDater.DateType.Modified.ToString
  335.            }
  336.  
  337.        End If
  338.  
  339.    End Sub
  340.  
  341.    ''' <summary>
  342.    ''' Restores at once all the preserved dates on the file.
  343.    ''' Note: Calling this method does not cause the deletion of any preserved date.
  344.    ''' </summary>
  345.    Public Sub Restore()
  346.  
  347.        Me.DisposedCheck()
  348.  
  349.        ' Creation
  350.        If Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then
  351.            Me._File.CreationTime = Me._PreservedCreationDate
  352.        End If
  353.  
  354.        ' Accessed
  355.        If Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then
  356.            Me._File.LastAccessTime = Me._PreservedLastAccessDate
  357.        End If
  358.  
  359.        ' Modified
  360.        If Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then
  361.            Me._File.LastWriteTime = Me._PreservedLastModifyDate
  362.        End If
  363.  
  364.    End Sub
  365.  
  366.    ''' <summary>
  367.    ''' Sets the specified dates on the file.
  368.    ''' Note:
  369.    ''' Calling this method does not cause the deletion of any preserved date.
  370.    ''' After setting a date, must call once the <see cref="Preserve"/> method if want to preserve any new date established.
  371.    ''' </summary>
  372.    ''' <param name="DateType">Indicates the type of dates to set on the file.</param>
  373.    ''' <param name="Date">Indicates the date.</param>
  374.    Public Sub [Set](ByVal DateType As DateType, ByVal [Date] As Date)
  375.  
  376.        Me.DisposedCheck()
  377.  
  378.        ' Creation
  379.        If DateType.HasFlag(FileDater.DateType.Created) Then
  380.            Me._File.CreationTime = [Date]
  381.        End If
  382.  
  383.        ' Accessed
  384.        If DateType.HasFlag(FileDater.DateType.Accessed) Then
  385.            Me._File.LastAccessTime = [Date]
  386.        End If
  387.  
  388.        ' Modified
  389.        If DateType.HasFlag(FileDater.DateType.Modified) Then
  390.            Me._File.LastWriteTime = [Date]
  391.        End If
  392.  
  393.    End Sub
  394.  
  395.    ''' <summary>
  396.    ''' Sets at once all the dates on the file.
  397.    ''' Note:
  398.    ''' Calling this method does not cause the deletion of any preserved date.
  399.    ''' After setting a date, must call once the <see cref="Preserve"/> method if want to preserve any new date established.
  400.    ''' </summary>
  401.    ''' <param name="Date">Indicates the date.</param>
  402.    Public Sub [Set](ByVal [Date] As Date)
  403.  
  404.        Me.DisposedCheck()
  405.  
  406.        Me._File.CreationTime = [Date]
  407.        Me._File.LastAccessTime = [Date]
  408.        Me._File.LastWriteTime = [Date]
  409.  
  410.    End Sub
  411.  
  412. #End Region
  413.  
  414. #Region " IDisposable "
  415.  
  416.    ''' <summary>
  417.    ''' To detect redundant calls when disposing.
  418.    ''' </summary>
  419.    Private IsDisposed As Boolean = False
  420.  
  421.    ''' <summary>
  422.    ''' Prevent calls to methods after disposing.
  423.    ''' </summary>
  424.    ''' <exception cref="System.ObjectDisposedException"></exception>
  425.    Private Sub DisposedCheck()
  426.  
  427.        If Me.IsDisposed Then
  428.            Throw New ObjectDisposedException(Me.GetType().FullName)
  429.        End If
  430.  
  431.    End Sub
  432.  
  433.    ''' <summary>
  434.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  435.    ''' </summary>
  436.    Public Sub Dispose() Implements IDisposable.Dispose
  437.        Dispose(True)
  438.        GC.SuppressFinalize(Me)
  439.    End Sub
  440.  
  441.    ''' <summary>
  442.    ''' Releases unmanaged and - optionally - managed resources.
  443.    ''' </summary>
  444.    ''' <param name="IsDisposing">
  445.    ''' <c>true</c> to release both managed and unmanaged resources;
  446.    ''' <c>false</c> to release only unmanaged resources.
  447.    ''' </param>
  448.    Protected Sub Dispose(ByVal IsDisposing As Boolean)
  449.  
  450.        If Not Me.IsDisposed Then
  451.  
  452.            If IsDisposing Then
  453.                InstancedFiles.Remove(Me._File)
  454.            End If
  455.  
  456.        End If
  457.  
  458.        Me.IsDisposed = True
  459.  
  460.    End Sub
  461.  
  462. #End Region
  463.  
  464. End Class
  465.  
  466. #End Region


« Última modificación: 22 Julio 2014, 05:37 am por Eleкtro » En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines