.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);

 

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

posted @   锦大大的博客呀!  阅读(664)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2020-09-29 网站优化之缓存--session和cache以及常用缓存应用之间的区别
点击右上角即可分享
微信分享提示