Encoding encode=Encoding.GetEncoding("GB2312"));
可以使用后附的类,先读文件的编码格式
encode = fileEncode.GetFileEncodeType("in_file.txt");
string strStr1 = File.ReadAllText("in.txt", encode);
StreamWriter sw = new StreamWriter("out.txt", false, Encoding.GetEncoding("ASCII"));
sw.Write("12.3");
sw.Close();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.IO;
using System.Configuration;
using System.Text;
namespace WebApplication1
{
//=1=按文件编码格式读写
public partial class _Default : System.Web.UI.Page
{
string proj_name = "";
protected void Page_Load(object sender, EventArgs e)
{
string xml_in_file="c:\\part.xml";//输入片段,其它程序生成的是一个节点
string xml_out_file="c:\\all.xml";//整体,新节点片段,要追加到其尾部
//1 读入输入文件的编码格式,并按其编码全部读入文本
Encoding encode1 = fileEncode.GetFileEncodeType(xml_in_file);
StringBuilder strSb1 = new StringBuilder();
string strStr1 = File.ReadAllText(xml_in_file, encode1);
//
StringBuilder strSb = new StringBuilder();
strSb.Clear();
//2 读入输出文件的编码格式,并按其编码全部读入文本
Encoding encode6 = fileEncode.GetFileEncodeType(xml_out_file);
strSb.AppendFormat("{0} \r\n", File.ReadAllText(xml_out_file, encode6));
strSb.Replace(strStr1, "");//旧的同名段落替换为空
//新节点片段,替换整体末尾标签,即是加入到末尾
strSb.Replace("</object_set>", strStr1 + "\r\n" + "</object_set>");//新的插入到末尾
// FileInfo myFile = new FileInfo(xml_out_file);
// StreamWriter sw = myFile.CreateText();
StreamWriter sw = new StreamWriter(xml_out_file, false, encode6);//Encoding.GetEncoding("GB2312"));
sw.Write(strSb.ToString());
sw.Close();
}
}
//=2=获得文件编码格式的类
public class fileEncode
{//获得文件编码格式的类
public static System.Text.Encoding GetFileEncodeType(string filename)
{
System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
Byte[] buffer = br.ReadBytes(2);
br.Close();
fs.Close();
if (buffer[0] >= 0xEF)
{
if (buffer[0] == 0xEF && buffer[1] == 0xBB)
{
return System.Text.Encoding.UTF8;
}
else if (buffer[0] == 0xFE && buffer[1] == 0xFF)
{
return System.Text.Encoding.BigEndianUnicode;
}
else if (buffer[0] == 0xFF && buffer[1] == 0xFE)
{
return System.Text.Encoding.Unicode;
}
else
{
return System.Text.Encoding.Default;
}
}
else
{
return System.Text.Encoding.Default;
}
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有