Search code examples
c#filepath

C# relative path not start from working directory


I have a C# program, it will read a file from a relative path ./report/report1.rdlc, however sometime for a unknown reason it found the file from a completely different place C:\Windows\system32\report\report1.rdlc but the file actually is place in C:\Program Files (x86)\Application1\report\report1.rdlc and the program is inside C:\Program Files (x86)\Application1\. Any reason the relative path not start from working directory?


Solution

  • It does start from the working directory. However, you shouldn't use the working directory, as it can vary if specific IO-Tasks (e.g. sometimes an Open File Dialog or (obviously) the Directory.SetCurrentDirectory method) are performed. Instead you should use the AppDomain.CurrentDomain.BaseDirectory property to get the path where the assembly file is located. You can use this like that:

    var relativePath = Path.Combine ("report", "report1.rdlc");
    var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
    var absolutePath = Path.Combine (baseDirectory, relativePath);
    

    Now you should work with the absolutePath to access the file.