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; } } }