2012-09-15 30 views
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); 
     } 

    } 
+1

你如何序列化這?你是否想要結束XML?二進制?其他一些格式?你已經有一些觸發保存設置的代碼? –

+0

@AnnaLear謝謝,我根據您的評論更新了問題和代碼。我不確定最好是通過二進制文件還是XML文件,我只是希望將m_settings字符串保存在某個地方,讓程序在保存文件後再次打開它時記住它。 –

回答

1

亞瑟,如果你的m_settings對象不復雜,你可以使用項目設置(應用程序或用戶級別)。下面是示例代碼如何保存一些項目設置的app.config:

 [YourNamespace].Properties.Settings.Default["MyProperty"] = "Demo Value"; 
    [YourNamespace].Properties.Settings.Default.Save(); 

如果你有二進制序列化的需求,你可以使用這樣的代碼: (序列化對象和繼承的對象必須標註作爲可序列化)

/// <summary> 
    /// Serializes object to file 
    /// </summary> 
    /// <param name="data"></param> 
    /// <param name="FilePath"></param> 
    public static void SerializeMyObject(object data, string FilePath) 
    { 
     System.IO.Stream stream = null; 
     try 
     { 
      stream = System.IO.File.Open(FilePath, System.IO.FileMode.Create); 
      System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bformatter = 
      new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 
      bformatter.Serialize(stream, data); 
      stream.Close(); 
      stream.Dispose(); 
     } 
     catch (Exception ex) 
     { 
      try 
      { 
       stream.Close(); 
       stream.Dispose(); 
      } 
      catch (Exception) 
      { 
      } 
      throw new Exception(ex.Message); 
     } 
    } 
相關問題