c#檔案操作

滄海一滴發表於2013-07-19

demo1:

        /// <summary>
        /// 將字串寫入到txt檔案
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="contentStr"></param>
        public void WriteTxt(string filepath,string contentStr) {
            if (!File.Exists(filepath))
            {
                logger.Info("檔案不存在");
                File.CreateText(filepath);
            }

            using (StreamWriter sw = new StreamWriter(filepath))
            {
                sw.WriteLine(contentStr);
            }
        }


        public string ReadTxt(string filepath)
        {
            StringBuilder sb = new StringBuilder(1024);
            string line;
            using (StreamReader sr = new StreamReader(filepath))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    sb.AppendLine(line);
                }
            }
            return sb.ToString();
        }