this.治疗完毕

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

c#文本文件读取并可控制读取行

private string 读文本()  
{  
    String 保存路径 = @System.Environment.CurrentDirectory + "\\特别日", 文件名 = @保存路径 + "\\特别日信息.txt ", 内容 = string.Empty; int 数 = 9;  
    if (Directory.Exists(保存路径))  
    {  
        FileInfo 文件 = new FileInfo(文件名);  
        if (文件.Exists)  
        {  
            using (FileStream 打开 = new FileStream(文件名, FileMode.Open))  
            {  
                using (StreamReader 读取 = new StreamReader(打开, Encoding.UTF8))  
                { while (!读取.EndOfStream) { 内容 += 读取.ReadLine(); /*~这里可修改控制读取指定行,设置一个INT变量用以判断和控制。*/ if(数-- == 0)break;} }  
            }  
       }  
    }  
    return 内容;  
}  
//调用:

[csharp] view plain copy
string 内容 = 读文本();  
[csharp] view plain copy
<a target=_blank href="http://www.lob.cn/jq/aspjq/6885.shtml" target="_blank">UTF8读取中文乱码参考转</a>:  
[csharp] view plain copy
        static Encoding 获取文本编码(FileStream 打开文件, Encoding 编码)  
        {  
            Encoding 获取编码 = 编码;  
            if (打开文件 != null && 打开文件.Length >= 2)  
            {//保存文件流的前4个字节  
                byte byte1 = 0, byte2 = 0, byte3 = 0;  
                long Seek位置 = 打开文件.Seek(0, SeekOrigin.Begin);//保存当前Seek位置   
                打开文件.Seek(0, SeekOrigin.Begin);  
                byte1 = Convert.ToByte(打开文件.ReadByte());  
                byte2 = Convert.ToByte(打开文件.ReadByte());  
                if (打开文件.Length >= 3)  
                    byte3 = Convert.ToByte(打开文件.ReadByte());  
                if (byte1 == 0xFE && byte2 == 0xFF)  
                    获取编码 = Encoding.BigEndianUnicode;  
                if (byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)  
                    获取编码 = Encoding.Unicode;  
                if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)  
                    获取编码 = Encoding.UTF8;  
                打开文件.Seek(Seek位置, SeekOrigin.Begin);//恢复Seek位置   
            }  
            return 获取编码;  
        }  
//调用:

[csharp] view plain copy
FileStream 打开 = new FileStream(文件路径, FileMode.Open);  
Encoding 取得这txt文件的编码 =  获取文本编码(打开, Encoding.GetEncoding("GB2312"));  
StreamReader 读取 = new StreamReader(打开, 取得这txt文件的编码)  
  
StreamWriter 写入 = new StreamWriter(保存文件名, true, Encoding.GetEncoding("GB2312"));//以可以追加文本的方式打开文件流  

 

posted on 2018-05-31 14:50  this.治疗完毕  阅读(971)  评论(0)    收藏  举报