对文本文件进行读写操作

对文本文件进行读操作

源作者:追风 人气:3486

using System;
using System.IO;

namespace ConsoleApplication2
{
    /// <summary>
    /// Summary description for Class2.
    /// </summary>
    public class Class1
    {
        private const string FILE_NAME = "MyFile.txt";
        public static void Main(String[] args)
        {
            if (!File.Exists(FILE_NAME)) //如果不文件存在,则抛出异常
            {
                Console.WriteLine("{0} does not exist!", FILE_NAME);
            }

            StreamReader sr = File.OpenText(FILE_NAME);
            String input;
            while ((input = sr.ReadLine()) != null)
            {
                Console.WriteLine(input);
            }
            Console.WriteLine("The end of the Stream has been reched.");
            sr.Close();
        }
    }
}

对文本文件进行写操作

源作者:追风 人气:3295

using System;
using System.IO;

namespace ConsoleApplication2
{
    /// <summary>
    /// Summary description for Class2.
    /// </summary>
    public class Class1
    {
        private const string FILE_NAME = "MyFile.txt";
        public static void Main(String[] args)
        {
            StreamWriter sr;
            string report;
            if (File.Exists(FILE_NAME)) //如果文件存在,则创建File.AppendText对象
            {
                sr = File.AppendText(FILE_NAME);
                report = "appended";
            }
            else  //如果文件不存在,则创建File.CreateText对象
            {
                sr = File.CreateText(FILE_NAME);
                report = "created";
            }

            sr.WriteLine("This is my first file.");
            Console.WriteLine("{0} {1}", FILE_NAME, report);
            sr.Close();
        }
    }
}
Contributors: FHL