c#如何读取txt文件内容
2014-04-11 20:59
281 查看
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.IO;
namespace test
{
public partial class Text : System.Web.UI.Page
{
//读取txt文件的内容
public string Gettext(string strfile)
{
string strout;
strout = "";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(strfile)))
{
Console.Write("没有找到文件!");
}
else
{
StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(strfile), System.Text.Encoding.Default);
String input = sr.ReadToEnd();
sr.Close();
strout = input;
}
return strout;
}
}
}
讲解一下StreamReader:
实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。
System.Text.Encoding.Default
类型:System.Text.Encoding
操作系统的当前 ANSI 代码页的编码。
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.IO;
namespace test
{
public partial class Text : System.Web.UI.Page
{
//读取txt文件的内容
public string Gettext(string strfile)
{
string strout;
strout = "";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(strfile)))
{
Console.Write("没有找到文件!");
}
else
{
StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath(strfile), System.Text.Encoding.Default);
String input = sr.ReadToEnd();
sr.Close();
strout = input;
}
return strout;
}
}
}
讲解一下StreamReader:
实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。
StreamReader(String, Encoding) | 用指定的字符编码,为指定的文件名初始化 StreamReader 类的一个新实例。 |
类型:System.Text.Encoding
操作系统的当前 ANSI 代码页的编码。
ReadToEnd | 从流的当前位置到末尾读取所有字符。 (重写 TextReader.ReadToEnd()。) |
StreamReader(String, Encoding) | 用指定的字符编码,为指定的文件名初始化 StreamReader 类的一个新实例。 |
相关文章推荐
- C#模拟鼠标键盘控制其他窗口
- C# 实现远程控制软件的关键技术
- C#打开网页
- C#复制文件夹的文件到另一个文件夹
- C# Win32API 模拟鼠标移动及点击事件
- C# Serializable(序列化)
- C#获取硬件信息
- c#读取个人签名到内存
- C#静态方法,静态变量
- C#对象序列化与反序列化
- C# List<T>用法
- c# 自定义类库与自定义控件
- C#常用方法类库:数据类型
- C#类的定义
- [C#]Attribute特性
- C#异常处理及心得
- C#中导出Excel的单元格属性设置
- C# WebService调用方法
- C#简单爬虫核心代码
- C#WebService 调用时报 Configuration System Failed to Initialize 或者 配置初始化失败