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

    • Are you passionate about ancient Indian sciences and looking for the best place to learn Vastu in Delhi? You're not alone! With the growing interest in holistic living and spiritual sciences, more and more learners are searching for authentic and structured ways to master Vastu Shastra. Whether you're a beginner or someone with basic knowledge, choosing the right course can make a big difference in your learning journey. When selecting a Vastu Shastra course in Delhi, consider the course content, teaching methodology, faculty expertise, and the blend of theoretical and practical training. It’s important that the course not only teaches the foundational principles but also covers real-life applications, including residential, commercial, and spiritual architecture based on Vastu. One highly recommended name in this field is the Bhartiya Institute of Vedic Science. Known for its traditional yet modern teaching approach, the institute offers detailed and well-structured courses suitable for students, professionals, and spiritual seekers alike. Has anyone here enrolled in a Vastu Shastra course in Delhi recently? How was your experience? What factors helped you decide on the institute or course structure? Sharing your insights could really help others make an informed choice.
    • Are you fascinated by how numbers influence your personality, decisions, and destiny? Welcome to "Soul Digits: Online Numerology Mastery"—an enlightening space for seekers, learners, and number enthusiasts to explore the ancient science of numerology in a modern, digital format. This online numerology course is not just about learning formulas or calculations. It's a journey of decoding your inner blueprint. From understanding life path numbers and destiny numbers to mastering name vibrations and compatibility insights, this course guides you step-by-step through the mystical world of numbers. Whether you’re a beginner or looking to deepen your practice, the curriculum is designed to be accessible and profound. What makes “Soul Digits” truly unique is its spiritual integration. Each number is not only a symbol but a mirror to your soul. You’ll discover how numbers relate to karmic lessons, hidden talents, career potential, and even your soul purpose. Many learners find themselves transforming not just their knowledge, but their lives. Discussions within this forum are focused on sharing insights, decoding charts, and helping each other grow through the collective wisdom of numerology. This is the place to begin if you're looking for a structured yet intuitive approach to mastering numbers online. And if you ever wish to pursue certification or in-depth study, platforms like the Bhartiya Institute of Vedic Science offer extended learning. Dive into the power of digits—your soul has a number. Let's discover it together.
    • je viens de redémarrez le 02/08/25 a 00:56 rien à changer 
    • je viens de confirmer cela, redémarrez votre ONT pour voir si c’est déjà le cas pour vous...
×
×
  • Créer...