Raniel Quirante
Raniel Quirante

Reputation: 431

How can I extract xml file encoding using streamreader?

I needed to get the encoding type from the top of the xml file

<?xml version=“1.0” encoding=“utf-8”?>

but only the encoding="utf-8" is needed

the "utf-8" only without the quotation mark, how can I achieve this using streamreader?

Upvotes: 1

Views: 881

Answers (4)

mehmetx
mehmetx

Reputation: 860

You need utf-8 or encoding="utf-8" ? this block returns utf-8 as a result. If you need encoding="utf-8", you need to change.

using (var sr = new StreamReader(@"yourXmlFilePath"))
{
    var settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };

    using (var xmlReader = XmlReader.Create(sr, settings))
    {
        if (!xmlReader.Read()) throw new Exception("No line");

        var result = xmlReader.GetAttribute("encoding"); //returns utf-8

    }
}

Upvotes: 2

Paweł Dyl
Paweł Dyl

Reputation: 9143

Since it's xml, I would recommend XmlTextReader that provides fast, non-cached, forward-only access to XML data and read just top of the xml file since declaration is there. See following method:

string FindXmlEncoding(string path)
{
    XmlTextReader reader = new XmlTextReader(path);
    reader.Read();
    if (reader.NodeType == XmlNodeType.XmlDeclaration)
    {
        while (reader.MoveToNextAttribute())
        {
            if (reader.Name == "encoding")
                return reader.Value;
        }
    }
    return null;
}

Upvotes: 1

Hyarus
Hyarus

Reputation: 952

const string ENCODING_TAG = "encoding"; //You are searching for this. Lets make it constant.


string line = streamReader.ReadLine();    //Use your reader here
int start = line.IndexOf(ENCODING_TAG);
start = line.IndexOf('"', start)+1;       //Start of the value
int end = line.IndexOf('"', start);       //End of the value
string encoding = line.Substring(start, end-start);

NOTE: This approach expects the encoding to be in the first line of an existing declaration. Which it does not need to be.

Upvotes: 1

mm8
mm8

Reputation: 169170

how can I achieve this using StreamReader?

Something like this:

using (StreamReader sr = new StreamReader("XmlFile.xml"))
{
    string line = sr.ReadLine();
    int closeQuoteIndex = line.LastIndexOf("\"") - 1;
    int openingQuoteIndex = line.LastIndexOf("\"", closeQuoteIndex);
    string encoding = line.Substring(openingQuoteIndex + 1, closeQuoteIndex - openingQuoteIndex);
}

Upvotes: 1

Related Questions