asp.net 解决文本中文乱码 各类文本编码转UTF-8 文本
/// <summary>
/// 解决文本中文乱码 各类文本编码转UTF-8 文本
/// </summary>
/// <param name="fullPath">原路径</param>
/// <param name="savePath">临时保存路径</param>
/// <param name="strnew">新的文件路径</param>
/// <returns>新文件路径</returns>
public static string GetUtf8(string fullPath,string savePath,string strnew)
{
Encoding e =GetFileEncodeType(fullPath);
System.IO.File.Create(savePath).Close();
using (StreamReader sr = new StreamReader(fullPath, e, false))
{
string utf8info = string.Empty;
Encoding utf8 = Encoding.UTF8;
// Convert the string into a byte[].
byte[] unicodeBytes = e.GetBytes(sr.ReadToEnd());
// Perform. the conversion from one encoding to the other.
byte[] asciiBytes = Encoding.Convert(e, utf8, unicodeBytes);
// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting tillustrate
// the use of GetCharCount/GetChars.
char[] asciiChars = new char[utf8.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
utf8.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
utf8info = new string(asciiChars);
using (StreamWriter sw = new StreamWriter(savePath, false, Encoding.UTF8))
{
sw.Write(utf8info);
}
}
System.IO.File.Delete(fullPath);
System.IO.File.Copy(savePath,strnew,true);
System.IO.File.Delete(savePath);
return strnew;
}
方法2
using (FileStream fs = new FileStream(fullPath, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs,Encoding.Default))
{
while (!sr.EndOfStream)
{
string sLine = sr.ReadLine();
//StringBuilder b = new StringBuilder();
//b.AppendLine(sLine);
//另存到其他txt文件中
using (StreamWritersw=System.IO.File.AppendText(savepath))
{
//string n = b.ToString();
sw.WriteLine(sLine.ToString());
}
}
}
}
System.IO.File.Delete(fullPath);
string strNewFile = fullPath;
System.IO.File.Copy(savepath, strNewFile, true);
System.IO.File.Delete(savepath);
//using (StreamReader sr = new StreamReader(strNewFile,Encoding.Default, false))
//{
// using (StreamWriter sw = new StreamWriter(fullPath, falsEncoding.UTF8))
// {
// sw.Write(Server.HtmlEncode(sr.ReadToEnd()));
// }
//}
//System.IO.File.Delete(strNewFile);
FileInfo fileNew = new FileInfo(strNewFile);
sourcesFile.File_Size = fileNew.Length;
this.sourcesFileService.Save(sourcesFile);
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。