Método File.SetLastWriteTime() en C# con ejemplos

File.SetLastWriteTime(String) es un método de clase de archivo incorporado que se utiliza para establecer la fecha y la hora en que se escribió por última vez el archivo especificado.
 

Sintaxis:  

public static void SetLastWriteTime (string path, DateTime lastWriteTime);

Parámetro: Esta función acepta dos parámetros que se ilustran a continuación: 
 

  • ruta: Este es el archivo especificado para el cual establecer la información de fecha y hora.
  • lastWriteTime: esta es la última fecha y hora de escritura local especificada de la ruta.

Excepciones:
 

  • ArgumentException: la ruta es una string de longitud cero, contiene solo espacios en blanco o uno o más caracteres no válidos según lo definido por InvalidPathChars.
  • ArgumentNullException: la ruta es nula.
  • PathTooLongException: la ruta especificada , el nombre de archivo o ambos superan la longitud máxima definida por el sistema.
  • FileNotFoundException: no se encontró la ruta especificada .
  • UnauthorizedAccessException: la persona que llama no tiene el permiso necesario.
  • NotSupportedException: la ruta tiene un formato no válido.
  • ArgumentOutOfRangeException: lastWriteTime especifica un valor fuera del rango de fechas u horas permitidas para esta operación.

A continuación se muestran los programas para ilustrar el método File.SetLastWriteTime(String, DateTime).
Programa 1: antes de ejecutar el siguiente código, se crea un archivo file.txt con algunos contenidos que se muestran a continuación: 
 

file.txt

CSharp

// C# program to illustrate the usage
// of File.SetLastWriteTime() method
 
// Using System and System.IO namespaces
using System;
using System.IO;
 
class GFG {
    public static void Main()
    {
        // Specifying a file
        string myfile = @"file.txt";
 
        // Calling the SetLastWriteTime() function
        // to set last written date and time
        File.SetLastWriteTime(myfile, new DateTime(2020,
                                         5, 4, 4, 5, 7));
 
        // Getting the last written date and time
        // of the file
        DateTime dt = File.GetLastWriteTime(myfile);
        Console.WriteLine("The last written date and "+
                     "time for this file was {0}.", dt);
    }
}

Producción: 
 

The last written date and time for this file was 5/4/2020 4:05:07 AM.

Programa 2: Inicialmente, no se creó ningún archivo. Debajo del código, el mismo crea un archivo file.txt e imprime la última fecha y hora escritas.
 

CSharp

// C# program to illustrate the usage
// of File.SetLastWriteTime() method
 
// Using System and System.IO namespaces
using System;
using System.IO;
 
class GFG {
    public static void Main()
    {
        // Specifying a file
        string path = @"file.txt";
 
        // Checking the existence of the file
        if (!File.Exists(path)) {
            File.Create(path);
        }
 
        // Calling the SetLastWriteTime() function
        // to set last written date and time
        File.SetLastWriteTime(path, new DateTime(2019,
                                      5, 4, 4, 5, 7));
 
        // Getting the last written date and time
        // of the specified file
        DateTime dt = File.GetLastWriteTime(path);
        Console.WriteLine("The last written date and "+
                     "time for this file was {0}.", dt);
    }
}

Ejecutando: 
 

The last written date and time for this file was 5/4/2019 4:05:07 AM.

Publicación traducida automáticamente

Artículo escrito por Kanchan_Ray y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *