C# 读取文本内容

C# 读取指定路径下的文本内容

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ConsoleApp17
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = ReadDoc("D:\\001.txt", Encoding.UTF8);
            Console.WriteLine(str);
            Console.Read();
        }

        /// <summary>
        /// 读取文本
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="encode">选择编码</param>
        /// <returns>返回读取文本</returns>
        public static string ReadDoc(string path, Encoding encode)
        {
            // 先判断路径文件是否存在
            if (!File.Exists(path))
            {
                throw new FileNotFoundException("Could not find file '" + path + "'.", path);
            }

            string result = "";
            using (StreamReader sr = new StreamReader(path, encode))
            {
                result = sr.ReadToEnd();  // 读取对象        
            }
            return result;
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="input">传入Stream</param>
        /// <param name="encode">选择编码</param> 
        /// <returns>返回读取文本</returns>
        public string ReadDoc(Stream input, Encoding encode)
        {
            // Stream 传入流为null
            if (input == null)
            {
                throw new ArgumentNullException("input", "Value cannot be null.");
            }

            string result = "";
            using (StreamReader sr = new StreamReader(input, encode))
            {
                result = sr.ReadToEnd();  // 读取对象        
            }
            return result;
        }
    }
}


作者最新文章
ASP.NET, ASP.NET Core WebApi 返回 Controller 返回 Json 类型结果
Visual Studio 调试 ASP.NET Core 无法连接 IIS Express 服务器
ASP.NET WebApi 与 ASP.NET Core WebApi 返回 HttpResponseMessage
SQL Server 中 CASE WHEN 使用
html table 设置表格背景图片,背景色