读写txt文件类

 public class TxtFileManage
    {
        public static void Save(string txt)
        {
            try
            {
                FileStream fileStream = new FileStream(CommonStatic.EmailTxtFilePath, FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.ReadWrite);
                StreamWriter sw = new StreamWriter(fileStream);
                sw.WriteLine(ReadFile() + "\n" + txt);
                sw.Close();
                fileStream.Close();
            }
            catch (Exception ex)
            {
                LogWriter.LogErrorEvent("Nagios", ex.Message);
            }
        }
        private static string ReadFile()
        {
            StringBuilder sb =new StringBuilder();
            if (File.Exists(CommonStatic.EmailTxtFilePath))
            {
                try
                {
                    FileStream fs = new FileStream(CommonStatic.EmailTxtFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    StreamReader sr = new StreamReader(fs);
                    String lineStr;
                    while ((lineStr = sr.ReadLine()) != null)
                    {
                        sb.AppendLine(lineStr);
                    }
                    sr.Close();
                    fs.Close();
                }
                catch (Exception ex)
                {
                    LogWriter.LogErrorEvent("Nagios", ex.Message);
                }
            }
            return sb.ToString();
        }
        public static Boolean IsContainTxt(string txt)
        {
            bool result = false;
            if(File.Exists(CommonStatic.EmailTxtFilePath))
            {
                try
                {
                    string[] contents = File.ReadAllLines(CommonStatic.EmailTxtFilePath, Encoding.Default);
                    foreach (string str in contents)
                    {
                        if (str.Trim() == txt.Trim())
                        {
                            result = true;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogWriter.LogErrorEvent("Nagios", ex.Message);
                }
            }
            return result;
        }
    }

转载于:https://www.cnblogs.com/zhangsongshan/archive/2013/05/03/3056157.html

你可能感兴趣的:(读写txt文件类)