-2

I'm trying to read some text from file

public void loadFromFile(string adress)
    {
        //int preventReadingEntireFile = 0;
        try
        {
            using (StreamReader sr = new StreamReader(adress))
            {
                //preventReadingEntireFile++;
                String line = sr.ReadToEnd();
                Console.WriteLine(preventReadingEntireFile + ": " + line);

                /*
                 * TODO: dodawanie słów do bazy
                 */
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }

But I don't know how to access this file (what the path is). I placed it in one of folers in my solution in my project. When I use "/TxtFiles/odm.txt" it searches for this file in "C:\TxtFiles\odm.txt" (which is wrong, there aren't any files like that there).

Is it possible? Do I have to make this file somehow "visible" for my scripts?

This is ASP.net mvc 5 project.

Patrick
  • 17,669
  • 6
  • 70
  • 85
Piotrek
  • 10,919
  • 18
  • 73
  • 136

2 Answers2

3

You have to use Server.MapPath() for it, which will generate absolute path of the file from relative url, the below code will work if TxtFiles directory is in root directory of Application:

StreamReader Sr = new StreamReader(Server.MapPath("~/TxtFiles/odm.txt"));

for you case:

string adress = "~/TxtFiles/odm.txt";
StreamReader Sr = new StreamReader(Server.MapPath(adress));
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

Looks like you're on Windows? A lot of programming languages (or rather, their file-handling libraries) interpret a starting slash '/' Unix-style, as "begin at the root of the file system", in your case, C:. Try doing "./TxtFiles/odm.txt", with an initial dot - this is conventionally interpreted as "start at the current directory".

Another option is to just use the full path, "C:\MyProjects\CurrentProject\TxtFiles\odm.txt".

Rolf Andreassen
  • 450
  • 1
  • 5
  • 9