简单文件读写

来源:互联网 发布:java输出当前系统时间 编辑:程序博客网 时间:2024/05/18 01:16
 

using System;

using System.IO;

using System.Text;

namespace ReadTxt

{

       /// <summary>

       ///简单的文件读写

       /// </summary>

       class Class1

       {

              /// <summary>

              /// Entry Point

              /// </summary>

              [STAThread]

              static void Main(string[] args)

              {

                     string path = Directory.GetCurrentDirectory() + "//Result//";

                     string date = DateTime.Now.ToLongDateString();

                     path += date + ".txt";

                     SafeWrite( path, "liujuejue" );

                     Console.WriteLine( SafeRead( path ) );

                     Console.ReadLine();

              }

 

              public static  string SafeRead( string path )

              {

                     StreamReader tr =  File.OpenText( path );

                     string temp = string.Empty;

                     string s = tr.ReadLine();

                     while( s != null )

                     {

                            temp += s;

                            s = tr.ReadLine();

                     }

                     tr.Close();

                     return temp;

              }

 

              public static void SafeWrite( string  path, string content )

              {

                     FileStream fs = null;

                     if( !File.Exists( path ) )

                     {

                            fs = File.Create( path );

                     }

                     else

                     {

                            fs = File.OpenWrite( path );

                     }

 

                     StreamWriter sw = new StreamWriter( fs );

                     sw.BaseStream.Position = fs.Length;

                     sw.WriteLine( content );

                     sw.Flush();

                     sw.Close();

                     fs.Close();

              }

       }

}

 
原创粉丝点击