解析StreamReader与文件乱码问题的解决方法

  public static Encoding GetEncoding(string filePath)

  {

  if (filePath == null)

  {

  throw new ArgumentNullException("filePath");

  }

  Encoding encoding1 = Encoding.Default;

  if (File.Exists(filePath))

  {

  try

  {

  using (FileStream stream1 = new FileStream(filePath, FileMode.Open, FileAccess.Read))

  {

  if (stream1.Length > 0)

  {

  using (StreamReader reader1 = new StreamReader(stream1, true))

  {

  char[] chArray1 = new char[1];

  reader1.Read(chArray1, 0, 1);

  encoding1 = reader1.CurrentEncoding;

  reader1.BaseStream.Position = 0;

  if (encoding1 == Encoding.UTF8)

  {

  byte[] buffer1 = encoding1.GetPreamble();

  if (stream1.Length >= buffer1.Length)

  {

  byte[] buffer2 = new byte[buffer1.Length];

  stream1.Read(buffer2, 0, buffer2.Length);

  for (int num1 = 0; num1 < buffer2.Length; num1++)

  {

  if (buffer2[num1] != buffer1[num1])

  {

  encoding1 = Encoding.Default;

  break;

  }

  }

  }

  else

  {

  encoding1 = Encoding.Default;

  }

  }

  }

  }

  }

  }

  catch (Exception exception1)

  {

  throw;

  }

  if (encoding1 == null)

  {

  encoding1 = Encoding.UTF8;

  }

  }

  return encoding1;

  }