Skip to content

Instantly share code, notes, and snippets.

@yetanotherchris
Created February 19, 2013 10:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yetanotherchris/4984662 to your computer and use it in GitHub Desktop.
Save yetanotherchris/4984662 to your computer and use it in GitHub Desktop.
Inserting XML into SQL Server without unicode issues
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
...
using (SqlConnection connection = new SqlConnection("conn string"))
{
connection.Open();
string sql = "INSERT INTO mytable (xmlColumn) VALUES (@xmlData)";
using (SqlCommand command = new SqlCommand(sql, connection))
{
// Swap round if the source file is unicode
string xml = File.ReadAllText(@"C:\myxml.xml");
//string xml = File.ReadAllText(@"C:\myxml.xml", Encoding.Unicode);
using (MemoryStream stream = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.Unicode))
{
writer.Write(xml);
writer.Flush();
stream.Position = 0;
SqlParameter parameter = new SqlParameter("@xmlData", SqlDbType.Text);
parameter.Value = new SqlXml(stream);
command.Parameters.Add(parameter);
command.ExecuteNonQuery();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment