Saturday, September 7, 2013

C# - Path class (Part 2)

Hi all, that’s the second article for the path class, this article will cover few more methods you can use to control your system objects.

Please read the first article for prerequisites needed to use this class

Controlling the file object

This paragraph will holds few code examples that can be used for controlling the file string (Name/Extension), this is relevant when you need to search objects by name or extension.

For all code examples in this paragraph I prepared a folder with few files:

Getting the file properties  

This code will show how to extract specific file properties using different methods of the class
The following methods will be used:
  • Getting the root path for the file
  • Getting the hosting folder
  • Getting the full path of the file
  • Getting the file name
  •  Getting the file extension
  •  Getting the full name

namespace ConsoleApplication4
    class Program
        static void Main(string[] args)
            int counter = 1;                  
            //Getting all files on folder 
            string[] FilesInFolder = Directory.GetFiles("C:\\DtVisionTech");
            //Getting the files properties using specific conditions          
            foreach (var filename in FilesInFolder)
                Console.ForegroundColor = ConsoleColor.Green;               
                Console.WriteLine("File number in folder: {0}\n", counter);
                Console.WriteLine("File Root drive : {0}", Path.GetPathRoot(filename));
                Console.WriteLine("File Directory name : {0}", Path.GetDirectoryName(filename));
                Console.WriteLine("File full path : {0}", Path.GetFullPath(filename));
                Console.WriteLine("Full file name: {0}", Path.GetFileName(filename));
                Console.WriteLine("File name : {0,3}", Path.GetFileNameWithoutExtension(filename));
                Console.WriteLine("File extension : {0}", Path.GetExtension(filename));                                              


No comments:

Post a Comment

My Presentations