How to read file in windows application root directory in C#.net?

22,472

Solution 1

By Using the Environment.CurrentDirectory

string yourpath = Environment.CurrentDirectory + @"\YourImage.jpg";
FileStream stream = new FileStream(yourpath, FileMode.Open, FileAccess.Read);
Image image = Image.FromStream(stream);
stream.Close(); 

Solution 2

Generally, you'd set those items to be copied into the bin folder. Right click in solution explorer/navigator, choose properties and set "Copy to output directory" to something different.

Share:
22,472
Kiran Solkar
Author by

Kiran Solkar

If something is worth doing once, it's worth building a tool to do it

Updated on February 20, 2020

Comments

  • Kiran Solkar
    Kiran Solkar about 4 years

    If i use Application.StartupPath or AppDomain.CurrentDomain.BaseDirectory It Search in a bin\debug folder for the file but I have to use a folder from my root directory "Resources\imagefile.png" in ma c# .net project!

    Filestream fs;
    fs = new Filestream(AppDomain.CurrentDomain.BaseDirectory + "folder\\imagefile.png");
    

    So how should write code to read file from my root directory in spite of using above code or a full path of the directory that is "@C:......." and even Server.MapPath is we cant use.

    To get my application path ,but this gives something like C:\Projects\XYZ\ABC\bin\Debug

    i don't want bin\Debug .Is there any way to achieve this ?

  • Kiran Solkar
    Kiran Solkar over 11 years
    If i set that file Copy to output directory from my folder but how should i read my root folder! then if i will make a setup file for ma program then can i retrieve those file from ma program??
  • spender
    spender over 11 years
    What do you mean by "root folder"? The folder where your .exe is?
  • Kiran Solkar
    Kiran Solkar over 11 years
    No its where outside bin folder where i run solution
  • abatishchev
    abatishchev about 11 years
    Use Path.Combine(Environment.CurrentDirectory, "YourImage.jpg") instead.
  • DSUK
    DSUK about 6 years
    as of VS2017 15.6 Environment.CurrentDirectory will return the directory of the executable.