现在的位置: 首页 > 综合 > 正文

C#中向文本文件写内容

2013年09月05日 ⁄ 综合 ⁄ 共 576字 ⁄ 字号 评论关闭
    //向文本文件写
    class WriteText
    {
        public static void Write_Text(string filename, string detail)
        {
            // Create an instance of StreamWriter to write text to a file.
            // The using statement also closes the StreamWriter.
            try
            {
                FileInfo fi = new FileInfo(filename);
                //if (!fi.Exists)
                //{
                //    fi.Create();
                //}
                FileStream fs = fi.OpenWrite();
                fs.Close();

                //StreamWriter sw = new StreamWriter(filename);//不可追加文本(直接覆盖)
                //StreamWriter sw = new StreamWriter(cfilename,true);//以可以追加文本的方式打开文件流
                StreamWriter sw = File.AppendText(filename);//以可以追加文本的方式打开文件流

                sw.WriteLine(detail);
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            //MessageBox.Show("OK!");
        }
    }

抱歉!评论已关闭.