IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

System.FormatException*: 'Le format de la chaîne d'entrée est incorrect.' [Débutant]


Sujet :

C#

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2022
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2022
    Messages : 15
    Points : 11
    Points
    11
    Par défaut System.FormatException*: 'Le format de la chaîne d'entrée est incorrect.'
    Bonjour, Bonsoir,

    Je travaille sur Visual Studio 2022 avec pour modèle : Application Windows Forms (.NET Framework).

    Mon programme consiste à venir envoyer certaines informations et en récupérer en les écrivant dans un fichier texte. Tout se déroule bien, j'appuie sur le bouton "bStart_Click", même après plusieurs appuie le fonctionnement se déroule correctement.

    Le problème vient lorsque je me déconnecte du port série avec le bouton "bDisconnect_Click" et que je relance la procédure sans fermer le logiciel.

    Le message d'erreur suivant survient :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    System.FormatException*: 'Le format de la chaîne d'entrée est incorrect.'
    en premier lieu ici :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    tensionVSET1 = float.Parse(indata, CultureInfo.InvariantCulture.NumberFormat);
    Voici une partie du code utiliser pour cela :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
     
    public partial class Form1 : Form 
    {
        float tensionVSET1, tensionVOUT1, courantISET1, courantIOUT1;
        string DataOUT, indata = "";
        string pathTestTxt = @"C:\Users\***\Desktop\***\test.txt";
        bool startError = false;
        private void si_DataReceived(string data) { tBox_ReceiveData.Text = data.Trim(); } // Permet d'ecrire dans la tBox_ReceiveData - Ports COM
        private delegate void SetTextDeleg(string text);
     
        public Form1() 
        {
            InitializeComponent();
        }
     
        private void Form1_Load(object sender, EventArgs e) 
        {
            string[] ports = SerialPort.GetPortNames();
            cBox_ComPort.Items.AddRange(ports);
        }
     
        private void bRefresh_Click(object sender, EventArgs e) 
        {
            cBox_ComPort.Items.Clear();
            string[] ports = SerialPort.GetPortNames();
            cBox_ComPort.Items.AddRange(ports);
        }
     
        private void bConnect_Click(object sender, EventArgs e) 
        {            
            try 
            {
                serialPort1.PortName = cBox_ComPort.Text;
                serialPort1.BaudRate = Convert.ToInt32(cBox_Baudrate.Text);
                serialPort1.DataBits = Convert.ToInt32(cBox_DataBits.Text);
                serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cBox_StopBits.Text);
                serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), cBox_Parity.Text);
     
                serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceivedHandler);
     
                serialPort1.Open();
     
                progressBar_Connect.Value = 100;
            } 
            catch (Exception err)  
            {
                MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
     
        private void bDisconnect_Click(object sender, EventArgs e) 
        {
            if (serialPort1.IsOpen) 
            {
                serialPort1.Write("OUT0");
                richTextBox_TestResult.Clear();
                tBox_GlobalResult.Clear();
                tBox_ReceiveData.Clear();
                tBox_GlobalResult.BackColor = Color.White;
                progressBar_Connect.Value = 0;
                tensionVSET1 = 0;
                tensionVOUT1 = 0;
                courantISET1 = 0;
                courantIOUT1 = 0;
                indata = "";
                serialPort1.Close();
            }
        }
     
        private void parseLine(string keyword, string lineStr)
        {
            string pathSaveTxt = @"C:\Users\***\Desktop\***\Save";
            string fileName = ("testSave" + NumericUpDown_SNR.Value + ".txt");
            pathSaveTxt = Path.Combine(pathSaveTxt, fileName);
     
            if (!File.Exists(pathSaveTxt))
                File.Create(pathSaveTxt).Close();
     
            StreamWriter sw = new StreamWriter(pathSaveTxt, true); // permet d'ecrire dans le fichier, true --> ajout du saut de ligne
     
            switch (keyword) 
            {
                case "tool1": //VSET1:X     --> X = Valeur de la tension - Definit la tension delivrée
                    command(keyword, lineStr);
                break;
     
                case "tool2": //VSET1? - obtient la tension de l'alimentation
                    command(keyword, lineStr);
                    tensionVSET1 = float.Parse(indata, CultureInfo.InvariantCulture.NumberFormat);
     
                    richTextBox_TestResult.AppendText("Tension alimentation: " + tensionVSET1 + "V" + Constants.vbCrLf);
                    sw.WriteLine("Tension alimentation: {0}V", tensionVSET1);
                break;
     
                case "tool3": //ISET1:X - Definit le courant delivré
                    command(keyword, lineStr);
                break;
     
                case "tool4": // ISET1? - obtient le courant de l'alimentation
                    command(keyword, lineStr);
                    courantISET1 = float.Parse(indata, CultureInfo.InvariantCulture.NumberFormat);
     
                    richTextBox_TestResult.AppendText("Courant alimentation: " + courantISET1 + "A" + Constants.vbCrLf); //+ indata + "A" + Constants.vbCrLf
                    sw.WriteLine("Courant alimentation: {0}A", courantISET1);
                break;
     
                case "tool5": //OUT1 - Active la sortie de l'alim
                    command(keyword, lineStr);
                break;
     
                case "tool6": //VOUT1? - obtient la tension de sortie
                    command(keyword, lineStr);
                    tensionVOUT1 = float.Parse(indata, CultureInfo.InvariantCulture.NumberFormat); // conversion string --> float
     
                    richTextBox_TestResult.AppendText(lineStr + " : " + tensionVOUT1 + "V"); 
                    sw.Write("{0}: {1}V --> ", lineStr, tensionVOUT1);
     
                    if (tensionVOUT1 >= 12) {
                        startError = true;
                        richTextBox_TestResult.AppendText(" --> ERROR" + Constants.vbCrLf);
                        sw.WriteLine("ERREUR");
                    } else {
                        richTextBox_TestResult.AppendText(" --> OK" + Constants.vbCrLf);
                        sw.WriteLine("OK");
                    }
                break;
     
                case "tool7": // IOUT1? - obtient le courant de sortie
                    command(keyword, lineStr);
                    courantIOUT1 = float.Parse(indata, CultureInfo.InvariantCulture.NumberFormat); // conversion string --> float
     
                    richTextBox_TestResult.AppendText(lineStr + " : " + courantIOUT1 + "A"); 
                    sw.Write("{0}: {1}A --> ", lineStr, courantIOUT1);
     
                    if (courantIOUT1 >= 0.2) {
                        startError = true;
                        richTextBox_TestResult.AppendText(" --> ERROR" + Constants.vbCrLf);
                        sw.WriteLine("ERREUR");
                    } else {
                        richTextBox_TestResult.AppendText(" --> OK" + Constants.vbCrLf);
                        sw.WriteLine("OK");
                    }
                break;
     
                default:
                break;
            }
            sw.Close();
            Console.ReadLine();
            Thread.Sleep(10);
        }
     
        private void command(string keyword, string lineStr)
        {
            Console.WriteLine(keyword);
            Console.WriteLine(lineStr);
     
            if (serialPort1.IsOpen)
                serialPort1.Write(lineStr);
     
            Thread.Sleep(200);
        }
     
        private void bStart_Click(object sender, EventArgs e) 
        {
            richTextBox_TestResult.Clear();
            startError = false;
            string lineStr = "";
            string keyword = "";
     
            foreach (string line in File.ReadLines(pathTestTxt)) 
            {
                keyword = line.Substring(0, line.IndexOf(" "));
                lineStr = line.Remove(0, keyword.Length);
                lineStr = lineStr.Remove(0, 1);
     
                parseLine(keyword, lineStr);
            }
     
            if (startError == true) {
                tBox_GlobalResult.BackColor = Color.Red;
                tBox_GlobalResult.Text = "ERROR";
            } else {
                tBox_GlobalResult.BackColor = Color.Green;
                tBox_GlobalResult.Text = "OK";
            }
            NumericUpDown_SNR.Value++;
            richTextBox_TestResult.AppendText(Constants.vbCrLf + "FIN DU TEST");
            Console.ReadLine(); // Suspend the screen.
            Thread.Sleep(10);
        }
    }
    J'ai essayé de voir avec :
    https://docs.microsoft.com/en-us/dot...e?view=net-6.0
    et
    https://docs.microsoft.com/en-us/dot...r?view=net-6.0

    Mais rien ne se passe, cela plante même lors de la première procédure.
    Je n'arrive pas très bien à comprendre.

    N'hésitez pas à me demander pour plus d'informations.
    Merci par avance de votre aide !

  2. #2
    Expert confirmé
    Avatar de popo
    Homme Profil pro
    Analyste programmeur Delphi / C#
    Inscrit en
    Mars 2005
    Messages
    2 674
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Analyste programmeur Delphi / C#
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2005
    Messages : 2 674
    Points : 5 259
    Points
    5 259
    Par défaut
    Même défaut que dans cette autre discussion :
    https://www.developpez.net/forums/d2...es-port-serie/

    Chaque fois que tu cliques sur le bouton "BConnect", tu ajoutes un évènement d'écoute du port série.
    Tu obtiens donc le même résultat : la deuxième lecture renvoie une chaine vide.

    Tu ne peux pas transformer une chaine vide en float.

  3. #3
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2022
    Messages
    15
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : France, Alpes Maritimes (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2022
    Messages : 15
    Points : 11
    Points
    11
    Par défaut
    Aaah oui d'accord ! Je n'avais pas vu ça comme cela. Beaucoup plus clair comme ça.

    Cela fonctionne ! Et je ne devrais plus avoir de problème en le plaçant lors de l'initialisation ici alors.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    public Form1() 
    {
        InitializeComponent();
        serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceivedHandler);
    }
    Merci encore une fois à toi popo !!

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 7
    Dernier message: 27/03/2019, 14h31
  2. Réponses: 6
    Dernier message: 27/05/2016, 21h58
  3. [Débutant] System.FormatException: Le format de la chaîne d'entrée est incorrect
    Par white_mind dans le forum ASP.NET
    Réponses: 1
    Dernier message: 30/08/2013, 21h28
  4. Réponses: 2
    Dernier message: 12/02/2009, 09h59
  5. [C#] [1.1] Le format de la chaîne d'entrée est incorrect
    Par Sup@Lou dans le forum Windows Forms
    Réponses: 2
    Dernier message: 08/08/2006, 10h01

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo