可用StreamReader类:
<script language="c#" runat="server">
void Page_Load(Object Src,EventArgs E) {
if (!IsPostBack){
string sfile1=Server.MapPath("a.txt");
StreamReader Sr1= new StreamReader((sfile1),Encoding.Default);
string ReadFile1=Sr1.ReadToEnd();
try{
ReadFile1 = ReadFile1.Replace(" "," ");
textbox1.Text+=ReadFile1;
Sr1.Close();
}
catch (Exception edd){
Console.WriteLine("[Count could not be obtained due to the following error]: " +edd.ToString()) ;
}
}
}
</script>
<script language="c#" runat="server">
void Page_Load(Object Src,EventArgs E) {
if (!IsPostBack){
string sfile1=Server.MapPath("a.txt");
StreamReader Sr1= new StreamReader((sfile1),Encoding.Default);
string ReadFile1=Sr1.ReadToEnd();
try{
ReadFile1 = ReadFile1.Replace(" "," ");
textbox1.Text+=ReadFile1;
Sr1.Close();
}
catch (Exception edd){
Console.WriteLine("[Count could not be obtained due to the following error]: " +edd.ToString()) ;
}
}
}
</script>
{
// Open and read the text file line by line
StreamReader srFile = new StreamReader(fileName,true);
while(srFile.Peek() > -1) // Check EOF
{
string sLine = srFile.ReadLine(); // Read one line
// ...
}
srFile.Close();
}
SQL Server有一个BCP工具用于从文本文件读入数据,
写进数据库中,T-SQL中有一个类似的Bulk Insert语句,可以实现同样的功能,
下面的函数将一个logFile中的内容读入WEBD表:
public void ImportLogFile(string logFile)
{
OleDbCommand cmd = new OleDbCommand() ;
cmd.Connection = Cn ; // Cn是数据库连接
// Use Bulk Insert statement
string sSQL = "BULK INSERT WEBD" ;
sSQL += " FROM '" + logFile.Replace("'","''") + "'" ;
sSQL += " WITH (" ;
sSQL += " DataFileType='char'" ;
sSQL += ",FieldTerminator=','" ;
sSQL += ",RowTerminator='\n'" ;
sSQL += ")" ;
// Run the Bulk insert
cmd.CommandText = sSQL ;
cmd.ExecuteNonQuery() ;
}
读取一个文本文件并写出 Sun Aug 2 06:34:07 1998
(注:textStream有关写的METHOD
Write(STRING)
WriteLine(STRING)
WriteBlankLines(LINES)
)
这是一个完整的程序
〈html〉
〈head〉
〈http-equiv="Content-Type" content="text/html;
charset=gb2312"〉
〈title〉〈/title〉
〈/head〉
〈body〉
< % LANGUAGE = VBScript %>
< %
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim filename
filename = "test.txt" '缺省相对路径是c:winnt
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(filename)
Set readf = f.OpenAsTextStream(ForReading,TristateFalse)
'第一个参数可选。输入/输出模式,是下列三个常数之一:
' ForReading=1只读、ForWriting=2 可读写或 ForAppending=3追加
'第二个参数也为可选。三个 Tristate 值之一,
' 指出以何种格式打开文件。忽略此参数,则文件以 ASCII
'格式打开。 TristateUseDefault=-2 以系统默认格式打开文件、
'TristateTrue=-1 以 Unicode 格式打开文件或TristateFalse=0
'以 ASCII 格式打开文件。
'也可用OpenTextFile方法打开文件
s = readf.ReadLine
Do While readf.AtEndOfLine <> True
s = readf.ReadLine
Response.write s & "" '逐行读文件并写出
Loop
readf.close
% >
< /body>
< /html>
这样就可以将文本文件读出并显示了。