I am trying to output a XML file by fetching data from a dataset. However, the xml file is always empty. Could you please help me to find the error in my code?
class Program
{
static void Main(string[] args)
{
string umail = "";
XDocument loaded = XDocument.Load(@"C:\1.xml");
var q = from c in loaded.Descendants("AdminUserDB.dbo.U_User")
select (string)c.Element("URI");
foreach (string em in q)
umail = em;
SqlConnection cn = new SqlConnection("server=(local);database=AdminUserDB;Persist Security Info=True; uid=sa;pwd=P@swrd123");
cn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM dbo.U_User WHERE URI=@umail", cn);
da.SelectCommand.Parameters.AddWithValue("@umail", umail);
da.Fill(ds);
string filename = "output.xml";
System.IO.FileStream myFileStream = new System.IO.FileStream(filename, System.IO.FileMode.Create);
System.Xml.XmlTextWriter myXmlWriter = new System.Xml.XmlTextWriter(myFileStream, System.Text.Encoding.Unicode);
ds.WriteXml(myXmlWriter);
myXmlWriter.Close();
cn.Close();
}
}
}
I am also trying to use DataSet.WriteXml method directly, however, I could not find which namespace should be referenced. I searched for WriteXml on MSDN, but I could not find the System.Data.DataSet namespace, which is listed on the WriteXml method page.
Thanks
SuT
Your code is leaking resources, always dispose disposable objects immediately. Otherwise you’ll be leaving files locked, and consume resources. Close doesn’t call Dispose.
If after calling dispose on your streams you still don’t see anything there’s prob no data.