C# txt读写类 TxtHelper

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Empty_Android/article/details/80778023

借鉴网上, 重新写了txt操作类

控制台程序

1. 目录结构


2. TxtHelper.cs

有两个成员函数, 读和写

如果文件路径不存在, 会新建

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace TxtHelper
{
    class TxtHelper
    {
        public TxtHelper()
        {
        }

        public void Write(string path, string content)
        {
            try
            {
                FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
                StreamWriter sr = new StreamWriter(fs);
                sr.WriteLine(content);
                sr.Close();
                fs.Close();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public string ReadFirstLine(string path)
        {

            if (!File.Exists(path))
                return "";

            try
            {
                FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
                StreamReader sr = new StreamReader(fs, Encoding.Default);
                String line = sr.ReadLine();

                return line;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

3. Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TxtHelper
{
    class Program
    {
        static void Main(string[] args)
        {
            Test();

            Console.ReadKey();
        }

        static void Test()
        {
            string path = "TimeStamp.txt";
            string content = "currenttime";

            TxtHelper txtHelper = new TxtHelper();
            txtHelper.Write(path, content);

            string line;
            line = txtHelper.ReadFirstLine(path);
            Console.WriteLine(line);
        }
    }
}

4. 执行结果


猜你喜欢

转载自blog.csdn.net/Empty_Android/article/details/80778023