c#文本文件读取

private string ReadFile1(string fPath)
    {
        //从指定的目录以打开或者创建的形式读取文件
        FileStream fs = new FileStream(fPath, FileMode.OpenOrCreate, FileAccess.Read);

        //定义输出字符串
        StringBuilder fContent = new StringBuilder();

        //初始化该字符串的长度为0
        fContent.Length = 0;

        //为上面创建的文件流创建读取数据流
        StreamReader read = new StreamReader(fs);

        //设置当前流的起始位置为文件流的起始点
        read.BaseStream.Seek(0, SeekOrigin.Begin);

        //读取文件
        while (read.Peek() > -1)
        {
            //取文件的一行内容并换行
            fContent.Append(read.ReadLine());
        }

        //关闭释放读数据流
        read.Close();

        ///返回读到的日志文件内容
        return fContent.ToString();
    }

    private string ReadFile2(string fPath)
    {
        if (!File.Exists(fPath))
        {
            return fPath + " 不存在";
        }

        // 创建StreamReader的实例,以读取文件内容
        using (StreamReader sr = new StreamReader(fPath))
        {
            string output=sr.ReadToEnd();
            sr.Close();
            return output;
        }
    }
    private string ReadFile3(string fPath)
    {
        StringBuilder fContent = new StringBuilder();

        if (!File.Exists(fPath))
        {
            return fPath + " 不存在";
        }
        using (StreamReader sr = File.OpenText(fPath))
        {
            String input;
            while ((input = sr.ReadLine()) != null)
            {
                fContent.Append(input);
            }
            sr.Close();
        }
        return fContent.ToString();
    }

posted @ 2012-10-27 10:08  therockthe  阅读(179)  评论(0)    收藏  举报