8

I want to open a txt file and read from it here's the code:

StreamReader reader = File.OpenText("TrackData/vehicle_points.txt"); 

TrckData is a folder in my web application. but i get this error :

Could not find a part of the path 'C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\TrackData\vehicle_points.txt'.

My project is not even in C Driver, I don't know where it gets that url.

0

5 Answers 5

10

ASP.Net applications are stored in a different folder, and here you have given a relative which may vary according to asp.net executable path.

Please use

 string path = Server.MapPath("TrackData/vehicle_points.txt"); StreamReader reader = File.OpenText(path); 

this will surely work..

Sign up to request clarification or add additional context in comments.

Comments

5

File.OpenText will start with the path being the current directory - this is the directory the executable is in.

You need to give it the correct full path to the file.

2 Comments

What if i wanted to run my project on another computer?
@rNuǝɹɐ - You still need to provide the full path. How you do that is up to you (pick up the root path from configuration, database, anything else).
3

Can use

StreamReader reader = File.OpenText(AppDomain.CurrentDomain.BaseDirectory.ToString() + "TrackData/" +fileName); 

1 Comment

This works great from a generic class file.
1
StreamReader sr = new StreamReader(Server.MapPath("~/TrackData/") + Textbox.Text); string read = sr.ReadLine(); if(read != null) { Response.Write(read); } else { Response.Write("nothing to display"); } 

1 Comment

Hi, welcome to stackoverflow!! I think your answer could be much more useful if you give an explanation of what was the error instead of dropping some code without any context. Please refer to How to answer
0

The best answer is the one:

string path = Server.MapPath("filename.txt"); StreamReader rd = new StreamReader(path); 

1 Comment

Perhaps you could add some text explaining why this answer is better than the one that 's already been accepted. using File or StreamReader are different things, so they can't really be compared.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.