C# Чтение из массива

342
23 февраля 2018, 15:21

Помогите понять почему вылетает с ошибкой "System.FormatException: Входная строка имела неверный формат." и там идут дальше много строк, и ругается всё это после того как я пытаюсь из строкового массива зачитать данные в сообщении или установить их в Label, что я делаю не так?

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Test2
{
/// <summary>
/// Description of MainForm.
/// </summary>
///
public partial class MainForm : Form
{
    public static string path_file = Application.StartupPath + "\\data.ini";

    public static class Win32
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int MessageBox(int hWnd, String text,
            String caption, uint type); 
        [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
        public static extern int GetPrivateProfileString(String sSection, String sKey, String sDefault,
            String sString, int iSize, String sFile);
    }
    //---------------------------------------
    public MainForm()
    {
        //
        // The InitializeComponent() call is required for Windows Forms designer support.
        //
        InitializeComponent();
        if (!System.IO.File.Exists(path_file))
        {
            Win32.MessageBox(0, "Файл с данными(data.ini) не найден! Найдите и установите файл в директорию программы, затем перезапуститесь!", "Уведомление", 0);
        }
        else
        {
            Win32.MessageBox(0, "Файл с данными(data.ini) найден! Удачной работы с программой!", "Уведомление", 0);
        }
        //
        // TODO: Add constructor code after the InitializeComponent() call.
        //
    }
    void Button1Click(object sender, EventArgs e)
    {
        if (!System.IO.File.Exists(path_file))
        {
            Win32.MessageBox(0, "Файл с данными(data.ini) не был найден! Найдите и установите файл в директорию программы, затем перезапуститесь!", "Уведомление", 0);
            return;
        }
        //-----------
        int[] norm_time = { 0, 0, 0, 0 };
        int[] lifeguard = { 0, 0, 0, 0 };
        string[] norm_name = { "easy", "moderate", "heavy", "very_heavy" };
        string[] key = { "text", "text" };
        //-----------
        for(int i = 0; i < 4; i++ )
        {
            Win32.GetPrivateProfileString(norm_name[i], "time", "NULL", key[0], 100, path_file);
            Win32.GetPrivateProfileString(norm_name[i], "lifeguard", "NULL", key[1], 100, path_file);
            if(key[0] == "NULL" || key[1] == "NULL")
            {
                Win32.MessageBox(0, "Ключ 'time' раздела 'easy' не был найден в данных, проверьте целостность файла!", "Уведомление", 0);
            }
            else
            {
                norm_time[i] = Convert.ToInt32(key[0]);
                lifeguard[i] = Convert.ToInt32(key[1]);
            }
        }
        label12.Text = (lifeguard.GetValue(3)).ToString();
    }
}

}

Answer 1

Завалялся класс из древнего проекта, возможно поможет Вам, хотя рекомендую всё-же json!

class Config
    {
        public string path;
        public Config(string INIPath)
        {
            path = INIPath;
        }
        public void Write(string Section, string Key, string Value)
        {
            NativeMethods.WritePrivateProfileString(Section, Key, Value, path);
        }
        public string Read(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = NativeMethods.GetPrivateProfileString(Section, Key, "", temp,
                                            255, path);
            return temp.ToString();
        }
    }
    internal static class NativeMethods
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        [return: MarshalAs(UnmanagedType.I4)]
        internal static extern int WritePrivateProfileString(string section,
            string key, string val, string filePath);
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        [return: MarshalAs(UnmanagedType.I4)]
        internal static extern int GetPrivateProfileString(string section,
                 string key, string def, StringBuilder retVal,
            int size, string filePath);
    }

далее всё просто вызываете метод write, или read, примерно так:

Config con = new Config(path);
var str = con.Read("section", "key"));
con.Write(section, key, value);

P/s и будет Вам счастье :-)

READ ALSO
Дописать текст в файл

Дописать текст в файл

Здраствуйте, я б хотел узнать, возможно ли записать данные в файлtxt формата в определенной позиции, что-то на примере бинарных файлов, где...

235
В потоке с переменной происходит какой-то бред!

В потоке с переменной происходит какой-то бред!

(recvd[0] - текст, recvd[1] - имя), это все работает в отдельном потоке

195
Не редактируются и не удаляются данные в БД, EF6 C# MVC

Не редактируются и не удаляются данные в БД, EF6 C# MVC

Добрый день! Подскажите как решить вопрос с записью в БД измененных данных или удалением ихДанные во view выводятся, в контроллер передаются,...

208
ASP.NET.После релиза пропадают папки

ASP.NET.После релиза пропадают папки

Добрый вечерЕсть проект на asp

200