Kamal Singh Kamal Singh - 1 month ago 12
C# Question

I need to save the XML file using linq with xml code in C#

I have written a simple C# code to produce a xml file and at-last save it in the pc destination where my current project exists in which i'm writing the code.But the problem is when i run the code then at the last line of code the exception is generated and shows that 'System.UnauthorizedAccessException' occurred in System.Xml.dll Additional information: Access to the path 'C:\Users\admin\Documents\Visual Studio 2013\Projects\ClassLibrary1\ClassLibrary1' is denied.Below is my code to generate and save xml file:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ClassLibrary1
{
class Class14
{
public static void Main()
{
XDocument xml = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Students",
new XElement("Student", new XAttribute("ID", 101),
new XElement("Name", "kamal"),
new XElement("Gender", "Male"),
new XElement("Marks", "800")),
new XElement("Student", new XAttribute("ID", 102),
new XElement("Name", "Sapna"),
new XElement("Gender", "Female"),
new XElement("Marks", "900")),
new XElement("Student", new XAttribute("ID", 103),
new XElement("Name", "Raju"),
new XElement("Gender", "Male"),
new XElement("Marks", "870"),
new XElement("Student", new XAttribute("ID", 104),
new XElement("Name", "Sushant"),
new XElement("Gender", "Male"),
new XElement("Marks", "700"))
)));
xml.Save(@"C:\Users\admin\Documents\Visual Studio 2013\Projects\ClassLibrary1\ClassLibrary1");

}
}
}




Answer

Seems like you don't have access to the path, try this out.

Provide XML file name,

xml.Save(@"C:\sample.xml");

if you want to store the file in project folder, Please follow this code, add System.Windows.Forms reference in your project.

string path = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Sample.xml");
Comments