How to Load Text File To String?
Loading text file to string is very common task. Here is the code that read text file from disc and store its content to string variable:
[ C# ]
using System;
// We need System.IO namespace to read and write to disc
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Gets full path to text file, in this example page will read itself
string FilePath = Server.MapPath("Default.aspx");
// Creates instance of StreamReader class
StreamReader sr = new StreamReader(FilePath);
// Finally, loads file to string
string FileContent = sr.ReadToEnd();
}
}
[ VB.NET ]
Imports System
Imports System.Web
' We need System.IO namespace to read and write to disc
Imports System.IO
Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Gets full path to text file, in this example page will read itself
Dim FilePath As String = Server.MapPath("Default.aspx")
' Creates instance of StreamReader class
Dim sr As StreamReader = New StreamReader(FilePath)
' Finally, loads file to string
Dim FileContent As String = sr.ReadToEnd()
End Sub
End Class
Instead of ReadToEnd() method that reads complete file, you can also use ReadLine() that reads next line or Read() method that reads next character.
Using of System.IO.File class to read text file
Instead of using StreamReader, as alternative you can use File class. Here is the code example that uses File class to read text file to string:
[ C# ]
using System;
// We need System.IO namespace to read and write to disc
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Gets full path to text file, this page will read itself
string FilePath = Server.MapPath("Default.aspx");
// Loads file to string
string FileContent = File.ReadAllText(FilePath);
}
}
[ VB.NET ]
Imports System
Imports System.Web
' We need System.IO namespace to read and write to disc
Imports System.IO
Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Gets full path to text file, this page will read itself
Dim FilePath As String = Server.MapPath("Default.aspx")
' Loads file to string
Dim FileContent As String = File.ReadAllText(FilePath)
End Sub
End Class
Related articles:
1. Mainpulating Files and Directories in ASP.NET