C#上位机模块之CSV存储类

13 篇文章 7 订阅
10 篇文章 0 订阅

在上位机中,经常会出现将数据存储到本地中,所以我写了一个常用的工具类用于直接调用,快速完成对CSV的存储。
工具类为非静态类,所以调用的时候需要新建对象去调用。
其中输入数据为:路径(string),题头(List),数据(List)
方法1:对项目debug路径下创建以时间为名字的CSV文件,并写入题头与数据
方法2:对绝对路径创建CSV文件,并写入题头与数据
方法3:对绝对路径的CSV文件追加数据
方法4:CSV保存时间,删除超出时间的路径
其中方法1与方法2是重载函数,使用时需要注意。
方法4在文件多的时候会出现运行时间慢的情况。其中测试时在100个文件中删除3个文件共耗时2.6ms。
方法1和2:在同一时间传入200个数据时耗时为0.99ms。
上述耗时仅作参考。

由于有人私信我新的方法,2023-3-28:新增3个方法
5.返回文件文件全部数据
6.返回文件最后一行数据
7.返回指定题头的列的全部数据,如果没有则返回-1

直接新建一个类,复制进去,然后修改命名空间即可

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

namespace SaveCSVFile//记得修改命名空间
{
    public class CreateCSV
    {
        /// <summary>
        /// 使用当前项目debug路径进行创建,名字为时间+CSV
        /// </summary>
        /// <param name="Title">题头</param>
        /// <param name="Data">数据</param>
        public void createCSV(List<string>Title,List<double>Data)
        {
            string now_str = System.AppDomain.CurrentDomain.BaseDirectory;
            string title = null ;
            //获取当前系统时间
            string datetime = DateTime.Now.ToString("yyyy-MM-dd")+"-"
                + DateTime.Now.Hour.ToString()+"-"+ 
                DateTime.Now.Minute.ToString()+"-"+DateTime.Now.Second.ToString();
            //创建文件并写入数据
            using (FileStream fsWrite = new FileStream(now_str + datetime+"CSV.csv",FileMode.OpenOrCreate,FileAccess.Write))
            {
                //写入题头
                foreach (var item in Title)
                {
                    title =title+item+",";
                }
                byte[] buffer = Encoding.UTF8.GetBytes(title);
                fsWrite.Write(buffer, 0, buffer.Length);//会将初始位置开始的字节进行覆盖
                fsWrite.Close();
                //写入数据
                using (StreamWriter sw = new StreamWriter(now_str + datetime + "CSV.csv", true))
                {
                    sw.Write("\r\n");
                    foreach (var item in Data)
                    {
                        sw.Write(item+",");
                    }
                }
            }
        }
        /// <summary>
        /// 使用绝对路径进行创建CSV
        /// </summary>
        /// <param name="str">输入的绝对路径值</param>
        /// <param name="Title">题头</param>
        /// <param name="Data">数据</param>
        public void createCSV(string str, List<string> Title, List<double> Data)
        {
            string title = null;
            //创建文件并写入数据
            using (FileStream fsWrite = new FileStream(str, FileMode.OpenOrCreate, FileAccess.Write))
            {
                //写入题头
                foreach (var item in Title)
                {
                    title = title + item + ",";
                }
                byte[] buffer = Encoding.UTF8.GetBytes(title);
                fsWrite.Write(buffer, 0, buffer.Length);//会将初始位置开始的字节进行覆盖
                fsWrite.Close();
                //写入数据
                using (StreamWriter sw = new StreamWriter(str, true))
                {
                    sw.Write("\r\n");
                    foreach (var item in Data)
                    {
                        sw.Write(item + ",");
                    }
                }
            }
        }
        /// <summary>
        /// 追加数据,写入下面的行
        /// </summary>
        /// <param name="str">输入的绝对路径值</param>
        /// <param name="Data">数据</param>
        public void AppendCSV(string str,List<double> Data)
        {
            //写入数据
            using (StreamWriter sw = new StreamWriter(str, true))
            {
                sw.Write("\r\n");
                foreach (var item in Data)
                {
                    sw.Write(item + ",");
                }
            }
            
        }
        /// <summary>
        /// 将保存时间外的文件进行删除
        /// </summary>
        /// <param name="Str">文件夹路径</param>
        /// <param name="Time">保存天数</param>
        public void SaveTime(string Str,int Time) 
        {

            DirectoryInfo theFolder = new DirectoryInfo(Str);  // 给出你的目录文件位置 
            FileInfo[] fileInfo = theFolder.GetFiles(); // 获得当前的文件夹内的所有文件数组

            string datetime = DateTime.Now.ToString("yyyy-MM-dd");//获取当前时间
            int now_day = ((int)(datetime[2] - '0') * 3650+ (int)(datetime[3] - '0') * 365 
                + (int)(datetime[5] - '0') * 10 + (int)(datetime[6] - '0') * 30
                + (int)(datetime[8] - '0') * 10 + (int)(datetime[9] - '0'));

            foreach (FileInfo NextFile in fileInfo)   //遍历文件
            {
                if (NextFile.Extension == ".csv")  // 得到你想要的格式
                {
                    FileInfo fi = new FileInfo(Str + "\\" + NextFile.Name);
                    string str_day = fi.CreationTime.ToString();
                    int day = ((int)(str_day[2] - '0') * 3650 + (int)(str_day[3] - '0') * 365
                + (int)(str_day[5] - '0') * 10 + (int)(str_day[6] - '0') * 30
                + (int)(str_day[8] - '0') * 10 + (int)(str_day[9] - '0'));
                    if(now_day-Time > day) 
                    {
                        File.Delete(Str+"\\"+NextFile.Name);//删除超出时间的文件
                    }
                }
            }
        }
        /// <summary>
        /// 读取绝对路径下的全部数据
        /// </summary>
        /// <param name="str">输入的绝对路径</param>
        /// <returns>返回全部字符,以\n换行为换行,,英文逗号为数字的间隔、</returns>
        public string ReadCSV(string str)
        {
            string CSVDate = null;
            using (StreamReader sr = new StreamReader(str,Encoding.UTF8)) 
            {
                while (!sr.EndOfStream)//判断是否读到文件最后,返回bool
                {
                    CSVDate= CSVDate+sr.ReadLine()+"\n";
                }
            }
            return CSVDate;
        }
        /// <summary>
        /// 读取绝对路径下CSV数据的最后一行
        /// </summary>
        /// <param name="str">绝对路径</param>
        /// <returns>返回CSV数据的最后一行</returns>
        public string ReadEndCSV(string str)
        {
            string CSVDate = null;
            using (StreamReader sr = new StreamReader(str, Encoding.UTF8))
            {
                while (!sr.EndOfStream)//判断是否读到文件最后,返回bool
                {
                    CSVDate =sr.ReadLine();
                }
            }
            return CSVDate;
        }
        /// <summary>
        /// 返回对应列的数据,如果没有对应的题头则返回-1
        /// </summary>
        /// <param name="str"></param>
        /// <param name="title"></param>
        /// <returns>列数据以,英文逗号分隔</returns>
        public string ReadColumnCSV(string str, string title)
        {
            string CSVDate = null;
            string time = null;
            List<string> columns_title = new List<string>();
            List<string> columns = new List<string>();
            int num = 0,lenth=0,n=0;
            using (StreamReader sr = new StreamReader(str, Encoding.UTF8))
            {
                CSVDate = sr.ReadLine();
                foreach (var item in CSVDate)
                {
                    if (item == ',')
                    {
                        columns_title.Add(time);
                        time = null;
                        continue;
                    }
                    time = time + item;
                }
                sr.Close();
            }
            lenth= columns_title.Count+1;
            if (columns_title.Contains(title))
            {
                foreach (var item in columns_title)
                {
                    if (item == title)
                        break;
                    num++;
                }
            }
            else
            {
                return "-1";
            }
            string quan=ReadCSV(str);
            time = null;
            foreach (var item in quan)
            {
                if (item == ','||item=='\n')
                {
                    if (item == '\n') n=n+2;
                    columns.Add(time);
                    time = null;
                    continue;
                }
                time = time + item;
            }
            int n_=0;
            for (int i = 0; i < columns.Count; i++)
            {
                title = title+",";
                if (i == (num+1+n_+ columns_title.Count * (n_ + 1)))
                {
                    title= title + columns[i]+ ",";
                    n_++;
                }
            }
            return title;
        }
    }
}

用法

//使用前,先创建CSV对象与题头,数据集合集合。
//str.Add(添加数据);
string now_str = System.AppDomain.CurrentDomain.BaseDirectory;//获取当前项目路径debug文件夹路径
   CreateCSV CSV=new CreateCSV();
        List<string> str = new List<string>();
        List<double> dou = new List<double>();
        //使用绝对路径的方法
        CSV.createCSV(now_str+"CSV.csv", str,dou);

后续如果还有什么需要增加可以评论区评论,如果我后面还遇到需要增加的方法再增加

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值