以编程方式创建xml文件

Raf*_*fay 5 c# xml

我试图创建一个xml文件,然后将其保存到文件位置...

string xmlPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "cities.xml";

XDocument doc = new XDocument(  
        new XElement("Cities",
            new XElement("City",
                new XAttribute("id", gid),
                new XElement("CityName", cityname))));
doc.Save(xmlPath);
Run Code Online (Sandbox Code Playgroud)

问题是它没有被保存到指定的位置......

mar*_*c_s 8

尝试使用该System.IO.Path.Combine方法确保a)在目录和文件名之间有必要的反斜杠,并且b)确保你没有多个:

string xmlPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, 
                                        "cities.xml");
Run Code Online (Sandbox Code Playgroud)

另外:也许您的用户帐户没有写入该目录的权限.尝试使用像隔离存储或其他目录这样的东西,你100%确定允许用户写入.


Dar*_*rov 3

代码看起来不错,当我在本地测试它时,它工作了。确保xmlPath指向当前用户具有写入权限的目录。作为旁注,最好使用Path.Combine