File.SetLastWriteTime(String, DateTime) Método

Definição

Define a data e a hora em que o arquivo especificado foi gravado pela última vez.

public:
 static void SetLastWriteTime(System::String ^ path, DateTime lastWriteTime);
public static void SetLastWriteTime(string path, DateTime lastWriteTime);
static member SetLastWriteTime : string * DateTime -> unit
Public Shared Sub SetLastWriteTime (path As String, lastWriteTime As DateTime)

Parâmetros

path
String

O arquivo para o qual definir as informações de data e hora.

lastWriteTime
DateTime

Um DateTime que contém o valor a ser definido para a última data e hora de gravação de path. Esse valor é expresso no horário local.

Exceções

Versões do .NET Framework e do .NET Core anteriores à 2.1: path é uma cadeia de caracteres de comprimento zero, contém apenas espaço em branco ou contém um ou mais caracteres inválidos. Você pode consultar caracteres inválidos usando o GetInvalidPathChars() método.

path é null.

O caminho especificado, o nome do arquivo ou ambos excedem o comprimento máximo definido pelo sistema.

O caminho especificado não foi encontrado.

O chamador não tem a permissão necessária.

path está em um formato inválido.

lastWriteTime especifica um valor fora do intervalo de datas ou horas permitidas para esta operação.

Exemplos

O exemplo a seguir verifica o sistema de arquivos para o arquivo especificado, criando o arquivo, se necessário, e, em seguida, define e obtém a hora da última gravação do arquivo.

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            string path = @"c:\Temp\MyTest.txt";
            if (!File.Exists(path))
            {
                File.Create(path);
            }
            else
            {
                // Take an action that will affect the write time.
                File.SetLastWriteTime(path, new DateTime(1985,4,3));
            }

            // Get the creation time of a well-known directory.
            DateTime dt = File.GetLastWriteTime(path);
            Console.WriteLine("The last write time for this file was {0}.", dt);
            
            // Update the last write time.
            File.SetLastWriteTime(path, DateTime.Now);
            dt = File.GetLastWriteTime(path);
            Console.WriteLine("The last write time for this file was {0}.", dt);
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
open System
open System.IO

try
    let path = @"c:\Temp\MyTest.txt"

    if File.Exists path |> not then
        File.Create path |> ignore
    else
        // Take an action that will affect the write time.
        File.SetLastWriteTime(path, DateTime(1985, 4, 3))

    // Get the creation time of a well-known directory.
    let dt = File.GetLastWriteTime path
    printfn $"The last write time for this file was {dt}."

    // Update the last write time.
    File.SetLastWriteTime(path, DateTime.Now)
    let dt = File.GetLastWriteTime path
    printfn $"The last write time for this file was {dt}."
with
| e -> printfn $"The process failed: {e}"
Imports System.IO
Imports System.Text

Public Class Test
    Public Shared Sub Main()
        Try
            Dim path As String = "c:\Temp\MyTest.txt"

            If File.Exists(path) = False Then
                File.Create(path)
            Else
                ' Take an action that will affect the write time.
                File.SetLastWriteTime(path, New DateTime(1985, 4, 3))
            End If

            ' Get the creation time of a well-known directory.
            Dim dt As DateTime = File.GetLastWriteTime(path)
            Console.WriteLine("The last write time for this file was {0}.", dt)

            ' Update the last write time.
            File.SetLastWriteTime(path, DateTime.Now)
            dt = File.GetLastWriteTime(path)
            Console.WriteLine("The last write time for this file was {0}.", dt)

        Catch e As Exception
            Console.WriteLine("The process failed: {0}", e.ToString())
        End Try
    End Sub
End Class

Comentários

O path parâmetro tem permissão para especificar informações de caminho relativas ou absolutas. As informações de caminho relativo são interpretadas como relativas ao diretório de trabalho atual. Para obter o diretório de trabalho atual, consulte GetCurrentDirectory.

Para obter uma lista de tarefas comuns de E/S, consulte Tarefas comuns de E/S.

Aplica-se a

Confira também