zoukankan      html  css  js  c++  java
  • .net core Api上传Txt文档读取并且解决乱码问题

    .net core Api上传Txt文档读取并且解决乱码问题

    一、直接先上关键:注意下方的strm 是 IFormFile file对象,并且此文只针对API上传TXT所处理。

      1. 读取的代码:

    using (StreamReader reader = new StreamReader(strm, Encoding.GetEncoding("GB2312")))
                    {
    
                        string line = null;
                        while ((line = reader.ReadLine()) != null)
                        {
                             //  line是读取到这一行的数据
                        }
                    }    

      2. 保存txt文件并且的代码:

    string name = Guid.NewGuid().ToString() + ".txt";
                            string filePath = "/Uploads/txt/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + name;
    
                            string rootPath = Directory.GetCurrentDirectory();
                            string path = $@"{rootPath}/Uploads/txt/" + DateTime.Now.ToString("yyyy-MM-dd");
                            string pathRq = $@"/Uploads/txt/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + name;
    
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
    
                            using (FileStream fs = System.IO.File.Create(path + "/" + name))
                            {
                                StreamWriter sw = new StreamWriter(fs);
                                string str = "123456"sw.WriteLine(str);
    
                                sw.Flush();
                                sw.Close();
                            }

    3. 如果导入的文件中存在中文,那么就会出现乱码问题。解决方案如下:

    1. 指定读取文件是GB2312
    using (StreamReader reader = new StreamReader(strm, Encoding.GetEncoding("GB2312")))
    2. 注入:Encoding到容器中
    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

    谢谢学习!!!关注我,共同进步

  • 相关阅读:
    常用正则表达式
    The Skins Factory 界面设计欣赏
    The Regulator 轻松上手
    Visual C#的Web XML编程
    业务流程不是需求
    如使用ODBC连接informix
    AJAX在信息系统中的应用研究
    浅谈几个SQL的日志概念
    量产 朗科(Netac)朗盛系列闪存盘E108 8G 手记
    【转】告诉大家他们是怎么成为富翁的
  • 原文地址:https://www.cnblogs.com/wangjinya/p/15352134.html
Copyright © 2011-2022 走看看