Skip to main content
 首页 » 编程设计

c#之XNA之保存 xml 文件时出现 UnauthorizedAccessException

2024年02月20日13傻小

在我的游戏过程中,您可以保存 map 并将 map 中的图 block 存储到xml文件中。
到目前为止没问题。当我尝试保存它时,问题就开始了,它以某种方式给我一个 UnauthorizedAccessException 错误。

文件夹位于我游戏的安装目录:

instal_dir/data/maps/

我进行了检查以确保文件夹已成功创建并具有正确的权限(写入、读取和执行)。

我做错了什么吗?

这是我的代码:

private void CreateXMLOfMap() 
{ 
    List<Tile> tiles = mapContainer.GetTileList(); 
    XmlDocument doc = new XmlDocument(); 
    XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); 
    doc.AppendChild(docNode); 
 
    XmlNode rootNode = doc.CreateElement("Map"); 
    doc.AppendChild(rootNode); 
 
    XmlNode mapName = doc.CreateElement("Name"); 
    mapName.AppendChild(doc.CreateTextNode("custom_map")); 
    rootNode.AppendChild(mapName); 
 
    XmlNode tilesNode = doc.CreateElement("Tiles"); 
    rootNode.AppendChild(tilesNode); 
 
    for (int i = 0; i < tiles.Count; i++ ) 
    { 
        XmlNode tileNode = doc.CreateElement("Tile"); 
        tilesNode.AppendChild(tileNode); 
 
        XmlNode positionNode = doc.CreateElement("Position"); 
        tileNode.AppendChild(positionNode); 
        XmlNode xNode = doc.CreateElement("X"); 
        xNode.AppendChild(doc.CreateTextNode(tiles[i].GetTilePosition().X.ToString())); 
        positionNode.AppendChild(xNode); 
        XmlNode yNode = doc.CreateElement("Y"); 
        yNode.AppendChild(doc.CreateTextNode(tiles[i].GetTilePosition().Y.ToString())); 
        positionNode.AppendChild(yNode); 
 
        XmlNode textureNode = doc.CreateElement("Texture"); 
        textureNode.AppendChild(doc.CreateTextNode(tiles[i].GetTileInfo().Name.ToString())); 
        tileNode.AppendChild(textureNode); 
 
        XmlNode YFrameNode = doc.CreateElement("YFrame"); 
        YFrameNode.AppendChild(doc.CreateTextNode(tiles[i].GetCurrentFrame().Y.ToString())); 
        tileNode.AppendChild(YFrameNode); 
    } 
 
    doc.Save(Constants.MAPS_DIRECTORY); 
} 

请您参考如下方法:

我认为问题是您没有以管理员身份运行应用程序,这会导致 UnauthorizedAccessException。所以你应该 force the system to run it as administrator .尝试更改应用程序 list 文件:

<requestedExecutionLevel level="asInvoker" uiAccess="false"/> 

到:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false"/> 

编辑:

How can I run the game with admin rights from visual studio?

有时,即使我是系统管理员,我在使用 vs2010 调试应用程序时也会遇到此异常。但是,如果您想以管理员身份调试应用程序,请尝试右键单击 visual studio 图标,然后以管理员身份运行。