Retrieving file path with C# during runtime PDF Print E-mail
Written by Administrator   
Sunday, 12 July 2009 11:54

1.Introduction

This article is pretty simple and I decided to write it to clarify some questions that i have answered in some forums, about how to get the path of an exe file during runtime using C#.

2.Code

To illustrate that, i made a project called: "myproject". What i want to achieve is getting the path of these three files(myfile1.txt, myfile2.dat and log.txt) that are inside my folder, during runtime, as shown in fig 1.

Fig 1. My application structure.

Code for class SystemFilePath.cs

 
namespace myproject
 {
 
   public enum FilePath
    {
        MyFile1,
        MyFile2,
        MyFile3,
    };
 
 
    class SystemFilePath
    {
 
        private static String path, appFile, appDir;
 
 
        public static string getFilePath(FilePath filePath)
        {
           path = {FNAMEL}">System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;
 
            appFile = AppDomain.CurrentDomain.ToString();
 
           appDir = path.Remove(path.LastIndexOf(appFile), appFile.Length);
 
           switch (filePath)
           {
               case FilePath.MyFile1:
                   return appDir + "myfile1.txt";
               case FilePath.MyFile2:
                   return appDir + "myfile2.dat";
               case FilePath.MyFile3:
                   return appDir + "log.txt";
               default:
                   return null;
           }
       }
   }
}
 
 
Code for class Program.cs

The explanation for this code is pretty straightforward. When running that, the code "System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase" will return the full path including the name of the executable that is running. I decided to place it on Program files -> myproject . So this code will return "//Program files//myproject/myproject.exe".
The code "AppDomain.CurrentDomain.ToString()" will return just the name of this application in this case "myproject.exe". Now to set just the application directory , i just removed the application name from the path "//Program files//myproject/myproject.exe" as it is possible to see on line 24. Now i just pass a enumeration to getFilePath and this method will return the full path to the file i want to select(including the file name).
Now calling this static method from my main method will generate the following output:

//Program files//myproject/myfile1.txt
//Program files//myproject/myfile2.dat
//Program files//myproject/log.txt
Last Updated on Friday, 06 August 2010 19:48