• 大小: 5KB
    文件类型: .cs
    金币: 2
    下载: 1 次
    发布日期: 2021-06-12
  • 语言: C#
  • 标签: C#  TXT  CSV  

资源简介

c# 读写txt文件和 csv文件,只需一条语句,文件放在可执行文件的文件夹下

资源截图

代码片段和文件信息

using OfficeOpenxml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AAAutoLoad.Classes
{
    public class FileRW:IDisposable
    {
        private static string FileDate { get; set; }
        private static string FilePath { get; set; }

        private static Dictionary TxtFileCollection = new Dictionary();
        private static Dictionary CsvFileCollection = new Dictionary();
        //private static ExcelPackage ep = new ExcelPackage();

        private static readonly object Lock = new object();
        
        public void Dispose()
        {
            foreach(var file in CsvFileCollection)
            {
                file.Value.Save();
            }
        }
        static FileRW()
        {
            FileDate = DateTime.Now.ToLongDateString();
            FilePath = System.Environment.CurrentDirectory + “\\Logs\\“;
            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }
        }
        public static void Write(string text string filename = ““)
        {
            
            string name = ““;
            string houzhui = ““;
            if (filename.Contains(‘.‘))
            {
                string[] nameArray = filename.Split(‘.‘);
                houzhui = nameArray[1].ToLower();
            }

            if (houzhui.Contains(“txt“))
            {
                name = DateTime.Now.ToString(“yyyy-MM-dd“) +“_“+ filename;
            }
            else
            {
                name = DateTime.Now.ToString(“yyyy-MM-dd“) +“_“+ filename + “.txt“;
            }

            string pa =  Path.Combine(FilePath  name);
            if(!TxtFileCollection.ContainsKey(name))
            {
                lock(Lock)
                {
                    FileStream filewrite = new FileStream(pa FileMode.OpenOrCreate FileAccess.ReadWrite);
                    TxtFileCollection.Add(name filewrite);
                }
            }

            StreamWriter strWrite = new StreamWriter(TxtFileCollection[name] Encoding.Unicode);
            string time = DateTime.Now.ToString(“HH:mm:ss“);

            TxtFileCollection[name].Seek(TxtFileCollection[name].Length SeekOrigin.Begin);

            string te = string.Format(“{0}   {1}\r\n“ time text);
            strWrite.WriteLine(te);
            strWrite.Flush();
            //strWrite.Close();

评论

共有 条评论