C# 文件数据流内容读取类StreamReader
程序设计界面
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace _6004_C_文件数据流内容读取类StreamReader
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnRead_Click(object sender, EventArgs e)
{
string msg = "";
string filePath = Application.StartupPath + @"\MyBooks.txt";
try
{
if (File.Exists(filePath))
{
using (StreamReader sr = new
StreamReader(filePath, Encoding.Default))
//Encoding.Default编码方式
{
long size = sr.BaseStream.Length;
int countLine = 0;
string result = "";
//亦可用while(sr.Peek() != -1)来判断
while (sr.EndOfStream != true)
{
result = result + sr.ReadLine() + "\n";
countLine = countLine + 1;
}
msg = msg + "文件位置:" + filePath + "\n";
msg = msg + "文件大小:" + size + " bytes \n";
msg = msg + "文件行数:" + countLine + " 行";
MessageBox.Show(msg, "StreamReader");
sr.Close();
rtxtContent.Text = result;
}
}
else
{
MessageBox.Show("[" + filePath + "]不存在.", "读取失败");
}
}
catch (IOException ex)
{
MessageBox.Show("错误消息:" + ex.Message, "IOException异常");
}
}
}
}