File time change

In this chapter you will learn:

  1. How to change file time
  2. Set file last write time

Change file time

File.SetLastAccessTime sets the date and time the specified file was last accessed.

using System;//j ava2  s  .  c o m
using System.IO;

class Test 
{
    public static void Main() 
    {
        try 
        {
            string path = @"c:\Temp\MyTest.txt";

            if (!File.Exists(path)) 
            {
                File.Create(path);
            }
            File.SetLastAccessTime(path, new DateTime(2010,5,4));
            DateTime dt = File.GetLastAccessTime(path);
            Console.WriteLine("The last access time for this file was {0}.", dt);
            File.SetLastAccessTime(path, DateTime.Now);
            dt = File.GetLastAccessTime(path);
            Console.WriteLine("The last access time for this file was {0}.", dt);
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

File.SetLastWriteTime

using System;/*j  av a  2 s . com*/
using System.IO;

class Test 
{
    public static void Main() 
    {
            string path = @"c:\Temp\MyTest.txt";
            if (!File.Exists(path)) 
            {
                File.Create(path);
            } 
            else 
            {
                File.SetLastWriteTime(path, new DateTime(2010,4,3));
            }
            DateTime dt = File.GetLastWriteTime(path);
            Console.WriteLine("The last write time for this file was {0}.", dt);
      
            File.SetLastWriteTime(path, DateTime.Now);
            dt = File.GetLastWriteTime(path);
            Console.WriteLine("The last write time for this file was {0}.", dt);
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Get creation time and access time
Home » C# Tutorial » File, Path
File creation
Deleting Files
Put to recycle bin
File Exists
File moving
File size
File attribute
Set file attribute
File time change
File time
Random file name
Temporary file
Path
Directory creation
Delete directory
Path existance
Change the path
Current Path
Directory listing
Recursive Path Listing
Combine path
Calculate Directory Size
Invalid path characters
System path
Directory copy
Drive
Drive information
File access rule
File System watcher