简单文件读写

    技术2022-05-11  69

    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();

                  }

           }

    }

     

    最新回复(0)