Geeks With Blogs
LD Express Quick Problem Solving Tutorials, Code Snippets and Tips in Enterprise Programming

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);
            }
        }
    }
}
Posted on Wednesday, April 7, 2010 1:44 PM | Back to top


Comments on this post: A Gentle .NET touch to Unix Touch

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © lavanyadeepak | Powered by: GeeksWithBlogs.net | Join free