C#中StreamReader和StreamWriter中文乱码问题

using System;
using System.IO;
using System.Text;

namespace ConsoleApp7
{
    class Program
    {
        static void Main(string[] args)
        {
            /*StreamReader和StreamWriter中文乱码问题*/

            var tempPath = "C:\\123.temple"; //确保该文件编码为ANSI或GB2312
            var targetPath = "C:\\123_bak.sql";
            string fileContent = string.Empty;
            StreamReader sr = null;
            FileStream fs = null;

            //读文件
            sr = new StreamReader(tempPath, Encoding.GetEncoding("GB2312"));  //指定GB2312编码        
            fileContent = sr.ReadToEnd();
            sr.Close();

            //写文件
            fs = new FileStream(targetPath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("GB2312")); //指定GB2312编码 
            fileContent += "\n这是添加的内容";
            sw.Write(fileContent);
            sw.Flush();
            sw.Close();
            fs.Close();

            //读取新文件
            sr = new StreamReader(targetPath, Encoding.GetEncoding("GB2312")); //指定GB2312编码 
            Console.WriteLine(sr.ReadToEnd());
            sr.Close();

            Console.ReadLine();
        }

    }
}

 

你可能感兴趣的:(Asp.net,&,C#)