C# 之 .net core 生成csv保存到本地

public Task Executes()
        {
            try
            {
                //Directory.GetCurrentDirectory() 获取项目的根文件夹,就是当前项目路径(这个我之前没有加,用的相对路径,系统匹配的路径写法不对,所以会报错)
                //@"\File\" 我在项目下建的文件夹,注意用反斜杠
                //DateTime.Now.ToString("yyyyMMdd") 今天日期
                string filePath = Directory.GetCurrentDirectory() + @"\File\" + DateTime.Now.AddDays(-1).ToString("yyyyMMdd"); //文件路径

                //如果没有这个文件夹就创建
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }
                
                List<string> datelist = new List<string>();//写入的数据
                datelist.Add("11"); datelist.Add("2222");var strRows = new StringBuilder();//数据拼写,这里是测试数据不多,但是真是情况基本是大量数据。所以要用StringBuilder
                for (int i = 0; i < datelist.Count(); i++)
                {
                    strRows.Append(datelist[i]);
                    strRows.Append("\r\n");//换行
                }


                string sExportFileName = DateTime.Now.AddDays(-1).ToString("yyyyMMdd") + ".csv"; //文件名
                string path = filePath + "\\" + sExportFileName;
                //检查是否有这个文件,没有创建文件,最后一定要Close,不然文件占用无法写入
                if (!File.Exists(path))
                {
                    File.Create(path).Close();
                }
                //写入文件
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(path, true))
                {
                    file.WriteLine(strRows);
                    file.Dispose();
                }

                return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

 

找到你刚才的文件夹就可以看到一个csv的文件,用记事本或者excle打开,就是刚才的数据啦

 对了最后写入文件的方法用这个也可以:

File.WriteAllText(path, strRows.ToString());

 

不愧是我!

 

posted @ 2020-03-19 16:56  #青鸟爱吃鱼  阅读(2748)  评论(0编辑  收藏  举报