| Answer: |
To read the contents of a text file use the StreamReader class like so:
' VB.NET Dim sr as New StreamReader("C:\SomeDir\SomeFile.txt")
Dim contents as String contents = sr.ReadToEnd()
// C# StreamReader sr = new StreamReader(@"C:\SomeDir\SomeFile.txt");
string contents = sr.ReadToEnd();
|
Note that this can be done in just two to three lines of code. First, we create an instance of the StreamReader class, specifying the physical path of the text file whose contents we want to read into a string. Next, we use the StreamReader's ReadToEnd() method to read the entire contents of the file as a string. That's all there is to it!
The File class is located in the System.IO namespace, meaning that you will have to import this namespace into your ASP.NET Web page or code-behind class. If you are using a server-side script block in your ASP.NET Web page, add <%@ Import Namespace="System.IO" %> to the top of the ASP.NET Web page. If you are using a code-behind class, add the following:
' VB.NET Imports System.IO
// C# using System.IO;
|
Realize that you can easily translate a virtual path, like /files/SomeFile.aspx to its corresponding physical path, say C:\InetPub\wwwroot\files\SomeFile.aspx using the Server.MapPath() method. For more information on Server.MapPath() be sure to read Using Server.MapPath. |