In Visual Basic, file handling is supported both through classic procedures (FileOpen, Input, Put, Close) and through .NET API (System.IO.StreamReader, StreamWriter, FileStream). It is preferred to use .NET classes.
Nuances:
Using statements to automatically free resources.StreamReader/StreamWriter for reading and writing strings, and FileStream for bytes.Code example:
Dim filePath As String = "test.txt" ' Writing to a file Using writer As New StreamWriter(filePath) writer.WriteLine("Hello, world!") End Using ' Reading from a file Using reader As New StreamReader(filePath) Dim content As String = reader.ReadToEnd() End Using
What will happen if you do not close the stream after writing to a file using StreamWriter, and why is it important to use the Using statement?
Answer:
If you do not close the stream (do not call Close or do not use Using), buffered data may not be written to the disk since the operating system keeps it in memory. An unclosed stream also holds the file descriptor, potentially blocking the file for other processes, and in long-running applications, this can lead to memory and resource leaks. The Using construct ensures that Dispose is called even when an exception occurs.
Story
Sudden data loss: When generating reports in a bank, the developer did not close
StreamWriter. As a result, part of the data was not written to the file due to the unfreed buffer, and the customer service department could not open the final reports.
Story
File descriptor leaks: In an ERP system, developers used manual file openings and often forgot to call
Close. After a few days, the application crashed due to exhausting the limit of open files.
Story
File lock conflict: In a network backup service, the file was opened without proper access mode, blocking access for other programs and causing prolonged downtime across the department.