【发布时间】:2012-03-02 03:41:41
【问题描述】:
public void SerializeObject(string filename, T data)
{
// Get the path of the save game
string fullpath = filename;
// Open the file, creating it if necessary
//if (container.FileExists(filename))
// container.DeleteFile(filename);
FileStream stream = (FileStream)File.Open(fullpath, FileMode.OpenOrCreate);
try
{
// Convert the object to XML data and put it in the stream
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(stream, data); //Thrown HERE
}
finally
{
// Close the file
stream.Close();
}
}
如何让上述代码停止抛出 InvalidOperationException?
完整的错误信息是: 无法生成临时类(结果=1)。 错误 CS0016:无法写入输出文件 'c:\Users[MYUSERNAME]\AppData\Local\Temp\czdgjjs0.dll' -- '访问被拒绝。
我不知道如何解决这个错误。
我正在尝试序列化我的 Level 类,如下所示:
[Serializable]
public class Level : ISerializable
{
public string Name { get; set; }
public int BestTime { get; set; } //In seconds
public List<Block> levelBlocks { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public Level()
{
}
public Level(SerializationInfo info, StreamingContext ctxt)
{
this.Name = (String)info.GetValue("Name", typeof(String));
this.BestTime = (int)info.GetValue("BestTime", typeof(int));
this.levelBlocks = (List<Block>)info.GetValue("Blocks", typeof(List<Block>));
this.Width = (int)info.GetValue("Width", typeof(int));
this.Height = (int)info.GetValue("Height", typeof(int));
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("Name", this.Name);
info.AddValue("BestTime", this.BestTime);
info.AddValue("Blocks", this.levelBlocks);
info.AddValue("Width", this.Width);
info.AddValue("Height", this.Height);
}
}
我的块类以类似的方式实现,只保存一个位置向量。
下面,我的保存方法:
public static void Save()
{
string filename = "saved.xml";
Level toSave = new Level();
toSave.levelBlocks = new List<Block>();
//TODO: build toSave
toSave.Name = "This is a level!";
toSave.BestTime = 0;
foreach (Entity e in EntityController.Entities)
{
if (e is Block)
{
toSave.levelBlocks.Add((Block)e);
if (e.Position.X > toSave.Width)
toSave.Width = (int)e.Position.X;
if (e.Position.Y > toSave.Height)
toSave.Height = (int)e.Position.Y;
}
}
serializer.SerializeObject(filename, toSave);
}
我的程序是一个 XNA 游戏。
【问题讨论】:
-
你能说出你怎么称呼
SerializeObject吗? -
根据 Sheldon 的回答,如果您使用的是 ASP.NET,请确保您的 IIS 工作进程有权访问 tempDirectory,否则会预先设置为专用文件夹。
标签: c# serialization