FileStream fs = new FileStream("MyFile.txt", FileMode.Open); //i think this explains itself
StreamReader sr = new StreamReader(fs); //you can initiate StreamReader with a string, and cut out instancing FileStream, but i don't - though i can't remember why.
string myFile = sr.ReadToEnd(); //myFile is now equal to the contents of MyFile.txt
Why do I get the error that the file cannot be found in
C:\WINNT\SYSTEM32? I am writing a web application in ASP.NET and I
thought that the default path was that of my web app (i.e.
C:\INETPUB\
to be absolutly sure of the location of a file, in respects to your program, first create the file from your program. use FileMode.CreateNew, and make sure you file has an interesting name; then save it to the location you would like to load from. leave your program, then track that file down - you'll soon work out where it is.
the errors you're getting are because you don't know where your file is. you create a new file so that you can give your self a reference point - an idea of where your program is trying to read files from.
I know exactly where my file is - I cut and pasted it into my web app folder as all other path references I have used in ASP.NET have required me to use this path. The file that I am trying to read from is C:\inetpub\
string filePath = System.AppDomain.CurrentDomain.BaseDirectory +
"email_files\email.txt"; //you may need to change the part in quotes depending on where you run your app from - ie: "secure\email_files\email.txt"
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
string myFile = sr.ReadToEnd();
Setting filePath picks up the path of the app you are running and then looks for the files you specify. Also means that nothing is hardcoded so if you are planning to publish anywhere else it will still function.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.