本篇内容介绍了“asp.net怎么解决文本中文乱码的问题”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
/// <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); }
“asp.net怎么解决文本中文乱码的问题”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。