關於讀取txt文件中文亂碼問題


在處理文件的過程中,讀取txt文件出現中文亂碼。這種情況是由於編碼字符不一致導致。

public static string ReadFile(string path, string fileName)
        {
            FileStream stream = null;
            StreamReader reader = null;
            StringBuilder v = new StringBuilder();

            try
            {
                stream = new FileStream(path + fileName, FileMode.Open);
                reader = new StreamReader(stream,Encoding.GetEncoding("GB2312"));

                string line = reader.ReadLine();
                do
                {
                    v.Append(line);
                    line = reader.ReadLine();
                }
                while (!string.IsNullOrEmpty(line));
            }
            catch
            {
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
            }
            return v.ToString();
        }

  轉換后可得正確結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM