1
我正在嘗試將m_settings
變量從volatile變量移到永久記錄。我曾嘗試將[serializable]
屬性添加到類中,並使用BinaryFormatter將m_settings
變量發送到文件流,但我得到了一個錯誤,說the file cannot be written, access to the file is denied
。我究竟做錯了什麼?使用BinaryFormatter在一個類中序列化一個String []變量
[Serializable]
public class SettingsComponent : GH_Component
{
public SettingsComponent(): base("LoadSettings", "LoadSettings", "Loading ini", "Extra", "Silkworm") { }
public override void CreateAttributes()
{
m_attributes = new SettingsComponentAttributes(this);
}
string m_settings_temp;
string[] m_settings;
public void ShowSettingsGui()
{
var dialog = new OpenFileDialog { Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*" };
if (dialog.ShowDialog() != DialogResult.OK) return;
m_settings_temp = File.ReadAllText(dialog.FileName);
m_settings = m_settings_temp.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
ExpireSolution(true);
}
protected override void SolveInstance(IGH_DataAccess DA)
{
if (m_settings == null)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "You must declare some valid settings");
return;
}
else
{
FileStream fs = new FileStream("DataFiletemp.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, m_settings);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
DA.SetDataList(0, m_settings);
}
}
你如何序列化這?你是否想要結束XML?二進制?其他一些格式?你已經有一些觸發保存設置的代碼? –
@AnnaLear謝謝,我根據您的評論更新了問題和代碼。我不確定最好是通過二進制文件還是XML文件,我只是希望將m_settings字符串保存在某個地方,讓程序在保存文件後再次打開它時記住它。 –