| Retrieving file path with C# during runtime |
|
|
|
| Written by Administrator |
| Sunday, 12 July 2009 11:54 |
1.IntroductionThis 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.CodeTo 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". //Program files//myproject/myfile1.txt |
| Last Updated on Friday, 06 August 2010 19:48 |


