Aller au contenu
Règlement du forum ×
IPTV et arnaques ×

Asp.net, comment lire et écrire sur un fichier text avec VB.net


getule

Messages recommandés

Il est presque toujours nécessaire lors du développement d'un site web de pouvoir écrire et lire sur des fichiers.

La procédure pour y arriver est relativement simple avec vb.net et c#.

Il suffit de faire appel à la classe à deux classes StreamReader et StreamWriter de l'espace de noms System.IO

 

 

StreamReader permet de lire un flux de caractères depuis un fichier.

StreamWriter permet d'écrire un flux de caractères sur un fichier.

 

 

Passons au code:

Tout d'aobord importons System.IO

Imports System.IO

 

 

Procédure de lecture:



Sub LireFichier()
              Dim MonSR As StreamReader  'déclaration d'une instance StreamReader
       Try
           MonSR = File.OpenText(Server.MapPath("Monfichier.txt")) 'ouverture du fichier
           Me.Literal1.Text =MonSR.ReadToEnd ' affichage des données du fichier dans un Literal
          MonSR.Close() 'Fermeture du StreamReader (à ne pas oublier)
       Catch ex As Exception


       End Try
   End Sub


 

 

Procédure d'écriture:

Sub EcrireFichier()

       Dim MonSR As StreamWriter = New StreamWriter(Server.MapPath("Monfichier.txt"))
       Try


           MonSR.Write(Me.TextBox1.Text) 'Ecriture du contenu du textbox sur mon fichier

           MonSR.Close()


       Catch ex As Exception


       End Try
   End Sub

 

 

et voila, source: http://forum.diafdz.com/yaf_postst23_Asp-net--comment-lire-et-ecrire-sur-un-fichier-text-avec-VB-net.aspx

Lien vers le commentaire
Partager sur d’autres sites

I think you're not handling exceptions really well here especially with file manipulation.

 

Let's take the code below, if for some reason the File.OpenText or ReadToEnd throws an exception your MonSR.Close will never be reached and will keep the stream in an invalid state.

 

Another thing is to always initialize variables before using them, it's a good practice and it helps with debugging.

 


Sub LireFichier()
              Dim MonSR As StreamReader  'déclaration d'une instance StreamReader
       Try
           MonSR = File.OpenText(Server.MapPath("Monfichier.txt")) 'ouverture du fichier
           Me.Literal1.Text =MonSR.ReadToEnd ' affichage des données du fichier dans un Literal
          MonSR.Close() 'Fermeture du StreamReader (à ne pas oublier)
       Catch ex As Exception
       End Try
   End Sub

 

 

The best way to do this is to Close the file handle in a Finally block like below and it sure will free the stream.


Sub LireFichier()
              Dim MonSR As StreamReader = Nothing  'déclaration d'une instance StreamReader
       Try
           MonSR = File.OpenText(Server.MapPath("Monfichier.txt")) 'ouverture du fichier
           Me.Literal1.Text =MonSR.ReadToEnd ' affichage des données du fichier dans un Literal
       Catch ex As Exception
       Finally
           If MonSR IsNot Nothing Then
               MonSR.Close()
           End If

       End Try
   End Sub


 

Same below, if the Write fails we make sure to close the handle to the file

 

Sub EcrireFichier()

       Dim MonSR As StreamWriter = New StreamWriter(Server.MapPath("Monfichier.txt"))
       Try


           MonSR.Write(Me.TextBox1.Text) 'Ecriture du contenu du textbox sur mon fichier

       Catch ex As Exception
       Finally
           If MonSR IsNot Nothing Then
               MonSR.Close()
           End If

       End Try
   End Sub

 

Happy coding.

Lien vers le commentaire
Partager sur d’autres sites

vous avez effectivement raison d'instancier le nouveau objet StreamReader et StreamWriter à l'interieur de try car pour une quelconque raison qui empêche la liaison au fichier, l'exception n'est pas portée. to^^^^ois, vous n'avez pas raison quand vous posez une condition pour finally alors que le catch permet ceci directement. donc je me rectifie :


[left][color=#000000][font=Consolas]Sub LireFichier()[/font][/color]
[color=#000000][font=Consolas]               Dim MonSR As StreamReader = Nothing  'déclaration d'une instance StreamReader[/font][/color]
[color=#000000][font=Consolas]        Try[/font][/color]
[color=#000000][font=Consolas]            MonSR = File.OpenText(Server.MapPath("Monfichier.txt")) 'ouverture du fichier[/font][/color]
[color=#000000][font=Consolas]            Me.Literal1.Text =MonSR.ReadToEnd ' affichage des données du fichier dans un Literal[/font][/color]
[color=#000000][font=Consolas]           MonSR.Close() 'Fermeture du StreamReader (à ne pas oublier)[/font][/color]
[color=#000000][font=Consolas]        Catch ex As Exception[/font][/color]
[color=#000000][font=Consolas]             [/font][/color]
[color=#000000][font=Consolas]        End Try[/font][/color]
[color=#000000][font=Consolas]    End Sub[/font][/color][/left]

 

et pour l’écriture:


[left][color=#000000][font=Consolas]Sub EcrireFichier()[/font][/color]


[color=#000000][font=Consolas]        Try[/font][/color]
[color=#000000][font=Consolas] Dim MonSR As StreamWriter = New StreamWriter(Server.MapPath("Monfichier.txt"))[/font][/color]
[color=#000000][font=Consolas]            MonSR.Write(Me.TextBox1.Text) 'Ecriture du contenu du textbox sur mon fichier[/font][/color]

[color=#000000][font=Consolas]            MonSR.Close()[/font][/color]

[color=#000000][font=Consolas]        Catch ex As Exception[/font][/color]
[color=#000000][font=Consolas] [/font][/color][color=#000000][font=Consolas]        End Try[/font][/color]
[color=#000000][font=Consolas]    End Sub[/font][/color][/left]

Modifié par getule
Lien vers le commentaire
Partager sur d’autres sites

Whoever looks at your code will notice the redundant code you added in the exception block. As I explained, the code inside Finally will execute either there is an exception or not, there is no need to add a second Close. BTW the compiler will optimize your code and will get rid of your second Close anyway.

Modifié par Darkvader
Lien vers le commentaire
Partager sur d’autres sites

  • 1 month later...

Rejoindre la conversation

Vous pouvez publier maintenant et vous inscrire plus tard. Si vous avez un compte, connectez-vous maintenant pour publier avec votre compte.

Invité
Répondre à ce sujet…

×   Collé en tant que texte enrichi.   Coller en tant que texte brut à la place

  Seulement 75 émoticônes maximum sont autorisées.

×   Votre lien a été automatiquement intégré.   Afficher plutôt comme un lien

×   Votre contenu précédent a été rétabli.   Vider l’éditeur

×   Vous ne pouvez pas directement coller des images. Envoyez-les depuis votre ordinateur ou insérez-les depuis une URL.

  • Messages

    • 2021 Associated Press Novice of the Year and Samuelsson Go To Nigerian Dining Establishment In NYCNew York Liberty ahead Michaela Onyenwere, 2021 Associated Press Newbie of the Year, goes to a Nigerian dining establishment in Brooklyn with prize-winning cook, business owner, writer and food activist Marcus Samuelsson on the most recent episode of Home Plate, the brand-new original shows series on the YES App, the YES Network's main this installment of Home base, Onyenwere, whose parents hail from Nigeria, and Samuelsson see Buka restaurant in Brooklyn, which concentrates on Nigerian cuisine. While there, she talks about with Samuelsson and Buka owner/chef Lookman Afolayan her hoping for home-cooked Nigerian meals and her interest for Nigerian society. Onyenwere also chats regarding fashion and her own line of by Samuelsson, Home base includes his coordinating with players from the New Yankees, Brooklyn Nets, New York Liberty and New York City FC, along with with celebs. Together, they check out New York City dining establishments focusing on food from the visitors' corresponding societies and family members heritages Esmery Martinez Jersey. The collection highlights the diverse societies and various foods represented in New York City restaurants, with Samuelsson and his guests discussing the vital duty that food has actually played in their is a brief clip from the YES App's Home Plate series is available to confirmed YES subscribers. The application can be downloaded and install below.
    • Looking for fun companions for night adventures? Authentic Ladies Premier Сasual Dating
    • Find a partner for a good time Actual Girls Superlative Сasual Dating
    • Performance speedtest en mars 2024 sur toutes les wilayas c'est nouveau ca y a même les communes 😁 https://www.speedtest.net/performance/algeria/algiers?fbclid=IwZXh0bgNhZW0CMTAAAR2EZ-br3gKlcAzx0oXT8UenXWtbjTkj2QOdqLLfd8yRosY_u6D3Q27_3ug_aem_AfH7waTumC2Pz7en4W640IUHAyksA4X4Y8nSL4ssJNIQNHEgNeqqnlcMWGkGeTzGHKhwthYFUiGePCB1KHW4DMP-
    • @XXX Proposer la carte chiffa sur un site internet...n'a rien d'une innovation. C'est juste un fichier jpeg...en ce qui me concerne! Si la cnad veut faire quelque-chose d'utile qu'ils élimine le papier pour les remboursements !!!!!!!!!!
×
×
  • Créer...