C#streamwriter拒绝将xml文件保存到MyDocuments中

时间:2017-05-23 08:12:17

标签: c# xml windows winforms streamwriter

我创建了一个小游戏,可以选择将角色保存到XML文件中,现在我希望Savegame-Folder位置位于MyDocuments,但每次我尝试保存XML时,我都会被拒绝访问StreamWriter的。有人知道如何解决这个问题吗?

这是我的代码:

 // Create the folder into MyDocuments (works perfectly!)

Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"Arena\Savegames\"));

// This one should the save the file into the directory, but it doesn't work :/

path = Path.GetDirectoryName(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Arena\Savegames\" + hero.created + ".xml"));

The Streamwriter:

public class SaveLoadGame
    {
        public void SaveGameData(object IClass, string filename)
        {
            StreamWriter saveGameWriter = null;
            try
            {
                XmlSerializer  saveGameSerializer = new XmlSerializer((IClass.GetType()));
                saveGameWriter = new StreamWriter(filename);
                saveGameSerializer.Serialize(saveGameWriter, IClass);
            }
            finally
            {
                if (saveGameWriter != null)
                saveGameWriter.Close();
                saveGameWriter = null;
            }
        }
    }

    public class LoadGameData<T>
    {
        public static Type type;

        public LoadGameData()
        {
            type = typeof(T);
        }

        public T LoadData(string filename)
        {
            T result;
            XmlSerializer loadGameSerializer = new XmlSerializer(type);
            FileStream dataFilestream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
            try
            {
                result = (T)loadGameSerializer.Deserialize(dataFilestream);
                dataFilestream.Close();
                return result;
            }
            catch
            {
                dataFilestream.Close();
                return default(T);
            }

        }
    }

我尝试了一些我在stackoverflow上找到的解决方案,如thisthis。但是没有为我工作,也许其他人知道如何访问该文件夹?或者只是将它保存在我实际可以访问的地方,因为ApplicationData和CommonApplicationData对我来说也不起作用。

顺便说一句,我使用Virtual Box和Win10_Preview,我希望不是因为这个原因。

编辑:在尝试将文件保存到MyDirectory之前,我设法将文件保存到项目的Debug文件夹中,如下所示:

path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Savegames\" + hero.created + ".xml";

gameSaver.SaveGameData(myCharacterObject, path);

1 个答案:

答案 0 :(得分:0)

感谢Jon Skeet我发现我只是使用目录名,而不是保存文件的完整路径。所以我只修改了代码:

 // Creating the folder in MyDocuments
Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"Arena\Savegames\"));

 // Setting the full path for my streamwriter
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Arena\Savegames\" + hero.created + ".xml";