前沿:最近学习c#记录遇到的问题
问题:报错CSV文件时,手动修改文件保存后再读取编码错误,上代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 数据保存读取
{
internal class Data
{
private string name;
private string sex;
private string age;
private string filePath
{
get
{
//获取当前文件相对路径
string path = Directory.GetCurrentDirectory() + "\\存储文件";
//判断是否存在文件夹,如果不存在走里面创建文件夹
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
return path;
}
set
{
}
}
public Data()
{
this.name = name;
this.sex = sex;
this.age = age;
}
public Data(string name, string age, string sex)
{
this.name = name;
this.sex = sex;
this.age = age;
}
public void SaveFile(string path)
{
//string newPath = filePath + "\\data.txt";
string newPath = filePath + path;
//创建文件写入流对象,参数: 1、当前文件路径 2、true追加写入false覆盖 3、编码格式
using (StreamWriter writer = new StreamWriter(newPath, true, Encoding.UTF8))
{
//换行写入数据
writer.WriteLine($"{name},{sex},{age},");
}
//using资源管理语法糖 等价下面
//StreamWriter writer = null;
//try
//{
// writer = new StreamWriter(path, true, encoding);
// writer.WriteLine($"{name},{sex},{age}");
//}
//finally
//{
// if (writer != null)
// writer.Dispose(); // 释放资源,关闭文件句柄
//}
}
public string[] ReadFile(string path)
{
//逐行读取
return File.ReadAllLines(filePath + path, Encoding.UTF8);
}
}
}
当保存txt或csv文件后,修改里面内容再次读取可能会造成编码导致数据丢失
解决
public Encoding DetectEncoding(string path)
{
using (var reader = new StreamReader(path, Encoding.Default, detectEncodingFromByteOrderMarks: true))
{
reader.Peek(); // 触发检测
return reader.CurrentEncoding;
}
}
如何使用
传入当前文件识别编码信息 替换掉StreamWriter对象第三个参数
public void SaveCsv(string path)
{
string newPath = filePath + path;
Encoding encoding = DetectEncoding(newPath); // 自动识别编码
using (StreamWriter writer = new StreamWriter(newPath, true, encoding))
{
writer.WriteLine($"{name},{sex},{age}");
}
}