A System.IO.FileNotFoundException is thrown anytime I try to read a file from my current directory

I am trying to read a file in my current directory but anytime I run I get a System.IO.FileNotFoundException. with the message could not find file'C:Program Files (x86)IIS Expresscn.config.

Below is my sample code….

string path = Path.Combine(Environment.CurrentDirectory, "cn.config");
        System.IO.StreamReader reader = new System.IO.StreamReader(path);

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The Current Directory will get the directory of the process running which in case of web app would IIS.exe or IISExpress.exe. You will need to get the path of executing assembly like :

string path = Path.Combine(
                        Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location
                          ), "cn.config");

or something like:

string path = Path.Combine(
              Path.GetDirectoryName(
              new System.Uri(
      System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath
                            )), "cn.config");


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x