發布時間:2020-08-06 15:23 作者:獨孤劍 閱讀:1966
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; } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞