A Gentle .NET touch to Unix Touch

Posted by lavanyadeepak on Geeks with Blogs See other posts from Geeks with Blogs or by lavanyadeepak
Published on Wed, 07 Apr 2010 11:44:58 GMT Indexed on 2010/04/07 18:03 UTC
Read the original article Hit count: 627

Filed under:

A Gentle .NET touch to Unix Touch

The Unix world has an elegant utility called 'touch' which would modify the timestamp of the file whose path is being passed an argument to  it. Unfortunately, we don't have a quick and direct such tool in Windows domain. However, just a few lines of code in C# can fill this gap to embrace and rejuvenate any file in the file system, subject to access ACL restrictions with the current timestamp.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace LavanyaDeepak.Utilities
{
    class Touch
    {
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Please specify the path of the file to operate upon.");
                return;
            }

            if (!File.Exists(args[0]))
            {
                
                try
                {
                    FileAttributes objFileAttributes = File.GetAttributes(args[0]);
                    if ((objFileAttributes & FileAttributes.Directory) == FileAttributes.Directory)
                    {
                        Console.WriteLine("The input was not a regular file.");
                        return;
                    }
                }
                catch { }

                Console.WriteLine("The file does not seem to be exist.");
                return;
                
            }

            try
            {
                File.SetLastWriteTime(args[0], DateTime.Now);
                Console.WriteLine("The touch completed successfully");
            }
            catch (System.UnauthorizedAccessException exUnauthException)
            {
                Console.WriteLine("Unable to touch file. Access is denied. The security manager responded: " + exUnauthException.Message);
            }
            catch (IOException exFileAccessException)
            {
                Console.WriteLine("Unable to touch file. The IO interface failed to complete request and responded: " + exFileAccessException.Message);
            }
            catch (Exception exGenericException)
            {
                Console.WriteLine("Unable to touch file. An internal error occured. The details are: " + exGenericException.Message);
            }
        }
    }
}

© Geeks with Blogs or respective owner