C#: Cycle through encodings

后端 未结 6 1499
小蘑菇
小蘑菇 2020-12-16 05:42

I am reading files in various formats and languages and I am currently using a small encoding library to take attempt to detect the proper encoding (http://www.codeproject.c

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 06:39

    How about something like this:

    public string LoadFile(string path)
    {
        stream = GetMemoryStream(path);     
        string output = TryEncoding(Encoding.UTF8);
    }
    
    public string TryEncoding(Encoding e)
    {
        stream.Seek(0, SeekOrigin.Begin) 
        StreamReader reader = new StreamReader(stream, e);
        return reader.ReadToEnd();
    }
    
    private MemoryStream stream = null;
    
    private MemorySteam GetMemoryStream(string path)
    {
        byte[] buffer = System.IO.File.ReadAllBytes(path);
        return new MemoryStream(buffer);
    }
    

    Use LoadFile on your first try; then use TryEncoding subsequently.

提交回复
热议问题