C#讀取文件,將文件內容以字符串的形式返回,使用FileStream類進行讀取。緩存
其中若要對字符串頻繁的追加時,StringBuilder比string類型要高效。ui
/// <summary> /// 讀取文件,返回相應字符串 /// </summary> /// <param name="fileName">文件路徑</param> /// <returns>返回文件內容</returns> private string ReadFile(string fileName) { StringBuilder str = new StringBuilder(); using (FileStream fs = File.OpenRead(fileName)) { long left = fs.Length; int maxLength = 100;//每次讀取的最大長度 int start = 0;//起始位置 int num = 0;//已讀取長度 while (left > 0) { byte[] buffer = new byte[maxLength];//緩存讀取結果 char[] cbuffer = new char[maxLength]; fs.Position = start;//讀取開始的位置 num = 0; if (left < maxLength) { num = fs.Read(buffer, 0, Convert.ToInt32(left)); } else { num = fs.Read(buffer, 0, maxLength); } if (num == 0) { break; } start += num; left -= num; str = str.Append(Encoding.UTF8.GetString(buffer)); } } return str.ToString(); }