Использование BinaryFormatter для сериализации переменной String[] в классе

Я пытаюсь переместить m_settings переменная от изменчивой до постоянных записей. Я попытался добавить [serializable] приписать класс и отправка m_settings переменная в файловый поток, используя BinaryFormatter, но я получил ошибку, говорящую, что the file cannot be written, access to the file is denied, Что я делаю неправильно?

[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 ответ

Решение

Артур, если твой объект 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);
        }
    }
Другие вопросы по тегам