黑馬程序員—C#關於文件的讀寫操作,可作爲系統日誌的記錄

----------------------Windows Phone 7手機開發、.Net培訓、期待與您交流! ----------------------

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace 文件操作
{ 
    class Program  
    {        
        static void Main(string[] args) 
        {            
            //創建一個文本文件,最好先判斷一下
            StreamWriter sw; 
            if (!File.Exists("templog.txt")) 
            {                 
                //不存在就新建一個文本文件,並寫入一些內容 
                sw = File.CreateText("templog.txt");  
                sw.Write("第一個字");        
                sw.WriteLine(" 跟隨老大的.");   
                sw.WriteLine("當前日期是:");    
                sw.WriteLine(DateTime.Now);       
            }           
            else           
            {    
                //如果存在就添加一些文本內容      
                sw = File.AppendText("templog.txt");   
                for (int i = 0; i < 10; i++)          
                {                    
                    sw.WriteLine("可以像平時輸出到屏幕一樣輸出{0}", i);   
                }         
            }         
            sw.Close();          
            //創建一個讀取器       
            StreamReader sr = new StreamReader("templog.txt");   
            //一次性讀取完   
            Console.WriteLine(sr.ReadToEnd());    
            Console.ReadLine();    
        }    
    }  
}

----------------------Windows Phone 7手機開發、.Net培訓、期待與您交流! ----------------------

詳細請查看:http://edu.csdn.net/heima
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章