我编写了一个简单的C#代码来生成一个xml文件,最后将它保存在当前项目所在的pc目的地中,我编写代码。但问题是当我运行代码时然后在最后一行代码中生成异常并显示' System.UnauthorizedAccessException'发生在System.Xml.dll中的附加信息:访问路径' C:\ Users \ admin \ Documents \ Visual Studio 2013 \ Projects \ ClassLibrary1 \ ClassLibrary1'被拒绝。下面是生成并保存xml文件的代码:
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");
}
}
}

答案 0 :(得分:1)
好像你无法访问路径,试试这个。
提供XML文件名
xml.Save(@"C:\sample.xml");
如果要将文件存储在项目文件夹中,请按照此代码在项目中添加System.Windows.Forms参考。
string path = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Sample.xml");
答案 1 :(得分:0)
我认为,如果您要写入此位置,您的应用必须以相应的凭据运行,例如,管理员。 然后你可以玩安全权,比如
var dir = "test_folder";
var fileName = Path.Combine(dir, "test.xml");
System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
string user = wi.Name;
MessageBox.Show(user);
DirectorySecurity dsec = Directory.GetAccessControl(dir);
dsec.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Modify, AccessControlType.Allow));
try
{
Directory.SetAccessControl(dir, dsec);
File.WriteAllText(fileName, "test");
}
catch (UnauthorizedAccessException uae)
{
MessageBox.Show(uae.Message);
}
catch (SecurityException se)
{
MessageBox.Show(se.Message);
}