Visualizzazione dei risultati da 1 a 5 su 5
  1. #1

    [c#] Classe StrameReader e file non esistente...

    Salve,
    sto usando molto le classi StreamReader e StreamWriter, particolarmente comode ed immediate. Con StreamReader c'è però il problema che quando il file che si tenta di aprire è inesistente genera un'eccezione. Esiste un modo per far si' che StreamReader crei automaticamente il file (vuoto, ovviamente) quando non lo trova, senza fargli generare l'eccezione?

    Grazie, ciao

  2. #2
    Utente di HTML.it L'avatar di cassano
    Registrato dal
    Aug 2004
    Messaggi
    3,002
    Apri il file in modalita appendorcreate.

  3. #3
    Originariamente inviato da cassano
    Apri il file in modalita appendorcreate.
    Come faccio a scegliere la modalità di apertura del file? Io solitamente faccio semplicemente:

    System.IO.StreamReader sr = new System.IO.StreamReader("NomeFile.txt");

    E poi uso i metodi sr.Read(), sr.ReadLine(), sr.ReadToEnd(), sr.ToString(), etc, etc.

    Grazie, ciao

  4. #4
    Utente di HTML.it L'avatar di cassano
    Registrato dal
    Aug 2004
    Messaggi
    3,002
    Leggete la guida......

    codice:
    Option Explicit On 
    Option Strict On
    Imports System
    Imports System.IO
    Class MyStream
        Private Const FILE_NAME As String = "Test.data"
        Public Shared Sub Main()
            ' Create the new, empty data file.
            If File.Exists(FILE_NAME) Then
                Console.WriteLine("{0} already exists!", FILE_NAME)
                Return
            End If
            Dim fs As New FileStream(FILE_NAME, FileMode.CreateNew)
            ' Create the writer for data.
            Dim w As New BinaryWriter(fs)
            ' Write data to Test.data.
            Dim i As Integer
            For i = 0 To 10
                w.Write(CInt(i))
            Next i
            w.Close()
            fs.Close()
            ' Create the reader for data.
            fs = New FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)
            Dim r As New BinaryReader(fs)
            ' Read data from Test.data.
            For i = 0 To 10
                Console.WriteLine(r.ReadInt32())
            Next i
            r.Close()
            fs.Close()
        End Sub
    End Class
    codice:
    Option Explicit On 
    Option Strict On
    Imports System
    Imports System.IO
    Imports Microsoft.VisualBasic
    Class DirAppend
        Public Shared Sub Main()
            Using w As StreamWriter = File.AppendText("log.txt")
                Log("Test1", w)
                Log("Test2", w)
                ' Close the writer and underlying file.
                w.Close()
            End Using
            ' Open and read the file.
            Using r As StreamReader = File.OpenText("log.txt")
                DumpLog(r)
            End Using
        End Sub
        Public Shared Sub Log(ByVal logMessage As String, ByVal w As TextWriter)
            w.Write(ControlChars.CrLf & "Log Entry : ")
            w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString())
            w.WriteLine("  :")
            w.WriteLine("  :{0}", logMessage)
            w.WriteLine("-------------------------------")
            ' Update the underlying file.
            w.Flush()
        End Sub
        Public Shared Sub DumpLog(ByVal r As StreamReader)
            ' While not at the end of the file, read and write lines.
            Dim line As String
            line = r.ReadLine()
            While Not line Is Nothing
                Console.WriteLine(line)
                line = r.ReadLine()
            End While
            r.Close()
        End Sub
    End Class

  5. #5
    Moderatore di Programmazione L'avatar di alka
    Registrato dal
    Oct 2001
    residenza
    Reggio Emilia
    Messaggi
    24,463

    Re: [c#] Classe StrameReader e file non esistente...

    Originariamente inviato da MonsterMash
    Esiste un modo per far si' che StreamReader crei automaticamente il file (vuoto, ovviamente) quando non lo trova, senza fargli generare l'eccezione?
    Ma perché una classe per la lettura di informazioni da un file, quale è StreamReader, dovrebbe fare anche una scrittura per creare appositamente un file che, peraltro, non contiene nulla?

    Non comprendo la logica. :master:

    Se il problema è gestire il possibile file mancante, questo si risolve con una intercettazione dell'eccezione. E' un po' come collegarsi ad un server esterno e comprarlo automaticamente nel caso in cui questo non esista, per non far fallire la chiamata al metodo di collegamento.
    MARCO BREVEGLIERI
    Software and Web Developer, Teacher and Consultant

    Home | Blog | Delphi Podcast | Twitch | Altro...

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.