C#读写指定编码格式的文本文件
在工作中经常读写文本文件,在读文件时,需要按开头的两个字节判断文件格式,然后按该格式读文件中的内容。
写文件时,也要按目标文件指定的格式来写入,只有这样才能让后续的环境正确读入。
1查看格式
在vs2010开发环境打开某个文件,然后从菜单上,文件--高级保存选项,就可看到当前文件的编码格式。
比如,xx.cs,xx.cshtml文件看到的是[简体中文(GB2312)-代码页936],就是GB2312。
xx.xml文件看到的是[Unicode(UTF-8带签名)-代码页65001],就是UTF-8。
常用的格式有:ASCII,UTF-8,UTF-7,UTF-32,Unicode,GB2312。
2读格式文件为
Encodingencode=Encoding.GetEncoding("GB2312")); 可以使用后附的类,先读文件的编码格式 encode=fileEncode.GetFileEncodeType("in_file.txt"); stringstrStr1=File.ReadAllText("in.txt",encode);
3写格式文件为
StreamWritersw=newStreamWriter("out.txt",false,Encoding.GetEncoding("ASCII")); sw.Write("12.3"); sw.Close();
4根据文件的编码格式读写文件的完整代码
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Xml; usingSystem.IO; usingSystem.Configuration; usingSystem.Text; namespaceWebApplication1 { //=1=按文件编码格式读写 publicpartialclass_Default:System.Web.UI.Page { stringproj_name=""; protectedvoidPage_Load(objectsender,EventArgse) { stringxml_in_file="c:\\part.xml";//输入片段,其它程序生成的是一个节点 stringxml_out_file="c:\\all.xml";//整体,新节点片段,要追加到其尾部 //1读入输入文件的编码格式,并按其编码全部读入文本 Encodingencode1=fileEncode.GetFileEncodeType(xml_in_file); StringBuilderstrSb1=newStringBuilder(); stringstrStr1=File.ReadAllText(xml_in_file,encode1); // StringBuilderstrSb=newStringBuilder(); strSb.Clear(); //2读入输出文件的编码格式,并按其编码全部读入文本 Encodingencode6=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>");//新的插入到末尾 //FileInfomyFile=newFileInfo(xml_out_file); //StreamWritersw=myFile.CreateText(); StreamWritersw=newStreamWriter(xml_out_file,false,encode6);//Encoding.GetEncoding("GB2312")); sw.Write(strSb.ToString()); sw.Close(); } } //=2=获得文件编码格式的类 publicclassfileEncode {//获得文件编码格式的类 publicstaticSystem.Text.EncodingGetFileEncodeType(stringfilename) { System.IO.FileStreamfs=newSystem.IO.FileStream(filename,System.IO.FileMode.Open,System.IO.FileAccess.Read); System.IO.BinaryReaderbr=newSystem.IO.BinaryReader(fs); Byte[]buffer=br.ReadBytes(2); br.Close(); fs.Close(); if(buffer[0]>=0xEF) { if(buffer[0]==0xEF&&buffer[1]==0xBB) { returnSystem.Text.Encoding.UTF8; } elseif(buffer[0]==0xFE&&buffer[1]==0xFF) { returnSystem.Text.Encoding.BigEndianUnicode; } elseif(buffer[0]==0xFF&&buffer[1]==0xFE) { returnSystem.Text.Encoding.Unicode; } else { returnSystem.Text.Encoding.Default; } } else { returnSystem.Text.Encoding.Default; } } } }
以上就是C#读写指定编码格式文本文件的方式方法,希望对大家的学习有所帮助。