C# 读写配置文档容易出现乱码的情况解决

C# 读写配置文档容易出现乱码的情况解决

1.上一篇博客提到了c#读写代码,但是未考虑到中文情况,运用上一篇博客提到的方法会造成读写中文都会出现乱码的情况。
2.参考博客:C# 读写INI文件中文乱码问题
3.直接附上代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace cfg
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("kernel32.dll")]
        private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);


        [DllImport("kernel32.dll")]
        private static extern long WritePrivateProfileString(string section, byte[] key, byte[] val, string filePath);
        private void button1_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + @"\app.cfg";//配置文档中的地址
            byte[] Buffer = new byte[1024];
            int bufLen = GetPrivateProfileString("SetpName", "FlowStart", "", Buffer, 1024, path);//读配置文档
            string s = Encoding.UTF8.GetString(Buffer, 0, bufLen);
            Console.WriteLine(s);

            WritePrivateProfileString("General", Encoding.UTF8.GetBytes("Port"), Encoding.UTF8.GetBytes("你好明天"), path);//写配置文档
        }
    }
}

4.图片
C# 读写配置文档容易出现乱码的情况解决_第1张图片

你可能感兴趣的:(c#基础知识,c#,开发语言,xhtml)