Reputation: 2378
I want to write a new XML file to disk but the following code gives an error.
static void Main(string[] args)
{
using (XmlWriter writer = XmlWriter.Create(@"C:\abc.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("Employees");
writer.WriteEndElement();
writer.WriteEndDocument();
}
Console.ReadKey();
}
Can anybody help me with this?
Note: abc.xml does not already exist.
Upvotes: 2
Views: 10902
Reputation: 311
For people who came here with exception
XmlWriter.Create() - Access to path denied
And you have the privilege to the given path you have mentioned, then have to check your file name as well. I had the issue when I was trying to create a file with no name or with no file extension. For these cases as well we will get the above mentioned exception
Upvotes: 0
Reputation: 21
Don't wanna necropost, but I just saw this post and I got the same error.
Turns out that the folder was set to:
This disallows C# to write to any of the files in your solution.
To fix this, go to:
Here is a link to what the above folder looks like:
Really stupid, but something easy to forget!
Upvotes: 2
Reputation: 3698
You can not write file into C:\
from VS without administrator mode. You need to run your application/VS in Admin mode to write file in C:\
. Or you can create one folder in C:\
and write file in that folder.
CODE
using (XmlWriter writer = XmlWriter.Create(@"C:\folder\abc.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("Employees");
writer.WriteEndElement();
writer.WriteEndDocument();
}
In above code you don't required to run application/VS in admin mode.
Note: C:\folder must exist otherwise it throws error.
If C:\folder
not exist add below code before writing file.
if (System.IO.Directory.Exists(@"C:\folder") == false)
{
System.IO.Directory.CreateDirectory(@"C:\folder");
}
Upvotes: 1
Reputation: 15813
Obviously, you don't have the right to access C:
. Choose a path you have access to or run the application with higher privileges.
As a side note, for most scenarios, it's not recommended to use System.Xml
anymore, use LINQ to XML (System.Xml.Linq
) instead:
new XElement("Employees").Save("abc.xml"); // and a path that you have access to.
Upvotes: 3
Reputation: 717
Depending on the system, you need administrator rights to create files @C:\
Run VS instante as administrator or change code to
using (XmlWriter writer = XmlWriter.Create("abc.xml"))
{
writer.WriteStartDocument();
writer.WriteStartElement("Employees");
writer.WriteEndElement();
writer.WriteEndDocument();
}
Upvotes: 2