1. 程式人生 > 實用技巧 >C# 讀取txt文字的內容

C# 讀取txt文字的內容

        public static void Read()
        {
            StreamReader sr = new StreamReader("D:\\test.txt", Encoding.GetEncoding("utf-8"));
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line.ToString());
            }
            Console.ReadKey();
        }

        
public static void Read1() { try { byte[] byData = new byte[100]; char[] charData = new char[1000]; FileStream file = new FileStream("D:\\test.txt", FileMode.Open); file.Seek(0, SeekOrigin.Begin); file.Read(byData,
0, 100); //byData傳進來的位元組陣列,用以接受FileStream物件中的資料,第2個引數是位元組陣列中開始寫入資料的位置,它通常是0,表示從陣列的開端檔案中向陣列寫資料,最後一個引數規定從檔案讀多少字元. Decoder d = Encoding.UTF8.GetDecoder(); d.GetChars(byData, 0, byData.Length, charData, 0); Console.WriteLine(charData); Console.ReadKey(); file.Close(); }
catch (IOException e) { Console.WriteLine(e.ToString()); Console.ReadKey(); } }