c# – Convert file content from XM file to UTF-16


In a C#-console app i’m reading XML files which are in a folder.

I’m getting the content from each file as a string and want to write it by Entity Framework to a SQL server table.

The table has three columns.

The first is an automatically incremented ID, the second a GUID and the third the content of the XML file.

The column for the content of the XML file is of type XML.

When i try to write a row into that table with the content of a XML file i’m getting the following exception:

“XML parsing: line 1, character 38, unable to switch the encoding”

The XML file has encoding UTF-8, but i think, that i need UTF-16.

How can i encode the file content in the right way?

Any help is welcome.

This is a typical header of the XML files:

<?xml version="1.0" encoding="utf-8"?>

And this is my code for writing the file content to SQL server:

public void WriteXmlTestFileToDatabase(string xmlFileContent)
{
    using (SqlServerDatabaseEntities db = new SqlServerDatabaseEntities())
    {
        var newEntry = new myTable();
        newEntry.FileGuid = Guid.NewGuid().ToString();
        newEntry.XmlDocument = xmlFileContent;
        db.myTable.Add(newEntry);
        db.Entry(newEntry).State = EntityState.Added;
        db.SaveChanges(); //Here i'm getting the exception
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *