- public static class TextFileReader
- {
- public static string ReadFile(string path)
- {
- FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read,
- FileShare.Read, 8192, FileOptions.SequentialScan);
- return ReadStream(stream);
- }
- public static string ReadStream(Stream stream)
- {
- byte[] bytes = new byte[stream.Length];
- long length = (stream.Length > 8192) ? (long)8192 : stream.Length;
- byte first;
- long pos = 0;
- bool is_utf8 = true;
- while (pos < length)
- {
- first = bytes[pos++] = (byte)stream.ReadByte();
- if (first < 192)
- {
- }
- else if (first < 224)
- {
- if ((length - pos > 1) &&
- (bytes[pos++] = (byte)stream.ReadByte()) < 128)
- {
- is_utf8 = false;
- break;
- }
- }
- else if (first < 240)
- {
- if ((length - pos > 2) &&
- !((bytes[pos++] = (byte)stream.ReadByte()) > 127
- && (bytes[pos++] = (byte)stream.ReadByte()) > 127))
- {
- is_utf8 = false;
- break;
- }
- }
- else
- {
- if ((length - pos > 3) &&
- !((bytes[pos++] = (byte)stream.ReadByte()) > 127
- && (bytes[pos++] = (byte)stream.ReadByte()) > 127
- && (bytes[pos++] = (byte)stream.ReadByte()) > 127))
- {
- is_utf8 = false;
- break;
- }
- }
- }
- if (pos < stream.Length)
- {
- stream.Read(bytes, (int)pos, (int)(stream.Length - pos));
- }
- if (is_utf8)
- {
- return Encoding.UTF8.GetString(bytes);
- }
- else
- {
- return Encoding.Default.GetString(bytes);
- }
- }
- }
Current language: English · also available in: Chinese (Simplified)