C#文本文件或其他文件新内容追加

以txt文本为例,以下代码实现a.txt文件中追加内容

FileStream mystream = new FileStream("C:\\a.txt", FileMode.OpenOrCreate);
            StreamWriter Mywriter = new StreamWriter(mystream, Encoding.Default);
            string text = "";
            for (int i = 0; i < axMSFlexGrid1.Rows; i++)
                for (int j = 0; j < axMSFlexGrid1.Cols; j++)
                    text += flex.get_TextMatrix(i, j) + "\t";
            Mywriter.Write(text);
            Mywriter.Close();
            mystream.Close();

这种方式也可以:

FileStream fs = null;
            string filePath = "C:\\file.txt";
            Encoding encoder = Encoding.UTF8;
            byte[] bytes = encoder.GetBytes("Hello World! \n\r");
            try
            {
                fs = File.OpenWrite(filePath);
               fs.Position = fs.Length;
              fs.Write(bytes, 0, bytes.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine("文件打开失败{0}", ex.ToString());
            }
            finally
            {
                fs.Close();
            }  


用的最多的还是这种

 StreamWriter sw=File.AppendText("c:\\Text.txt");
 sw.WriteLine("13");
 sw.WriteLine("22222");
 sw.WriteLine("88888");
 sw.Flush();
 sw.Close();

 

posted @ 2015-01-26 15:35  童心少年  阅读(2930)  评论(0编辑  收藏  举报