C#操作文本和目录

源代码地址https://github.com/junkai-li/NetCoreKevin
基于NET6搭建跨平台WebApi架构支持单点登录、多缓存、自动任务、分布式、多租户、日志、授权和鉴权 、网关 注册与发现、CAP集成事件、领域事件、 docker部署

C#操作文本和目录

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace DateupLoad.IOMain
{
    public class IoText
    {
        /// <summary>
        /// 获取指定名字文本框中的值
        /// </summary>
        /// <param name="name"></param>
        public static string GetNameText(string name)
        { 
            try
            {
                string line;
                // 创建一个 StreamReader 的实例来读取文件 
                // using 语句也能关闭 StreamReader
                string path = Environment.CurrentDirectory + @"\ModelIDText";
                //目录是否存在
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path+= "\\"+name + ".txt";
                if (System.IO.File.Exists(path)== false)//如果不存在就创建file文件夹
                {
                    InsertText(name, "0");
                }
                using (StreamReader sr = new StreamReader(path))
                {
                   
                    while ((line = sr.ReadLine())!=null)
                    {
                       
                        line += sr.ReadLine();
                        if (line != null)
                        {
                            return line;
                        }
                    }
                    
                    return "0";
                }
            }
            catch (Exception e)
            {
                // 向用户显示出错消息
                Console.WriteLine("The file could not be read:");
                return "文本未找到";
            } 
        }
        /// <summary>
        /// 存入Text
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public static void InsertText(string name, string value)
        {
            //创建文件, 如果文件已存在,将被覆盖
            string path = Environment.CurrentDirectory + @"\ModelIDText";
            //目录是否存在
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path+="\\" + name + ".txt";
            FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.Write);
            StreamWriter sw0 = new StreamWriter(fs1);
            sw0.WriteLine(value);//开始写入值
            sw0.Close();
            sw0.Dispose();
            fs1.Close();
            fs1.Dispose();
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值