删除log文件末尾中指定的行数

时间:2023-03-09 02:13:50
删除log文件末尾中指定的行数

/// <summary>
        /// 删除log文件末尾中指定的行数
        /// </summary>
        /// <param name="file">文件路径</param>
        /// <param name="line">删除的行数</param>
        public static void deleteLogToLine(string file,int line)
        {
            System.IO.StreamReader st= new StreamReader(file, System.Text.Encoding.Default);

int lineCount = 0;//总行数
            List<string> data = new List<string>();
            while (true)
            {
                string str = st.ReadLine();
                if (str == null || str.Length == 0) break;
                data.Add(str);
                lineCount++;
            }
            st.Close();
            st.Dispose();

StreamWriter sw = new StreamWriter(file, false);
            for (int i = 0; i < data.Count - line; i++)
            {
                sw.WriteLineAsync(data[i]);
            }
            sw.Flush();
            sw.Close();
        }