This opens the file with read-only access
Imports System
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Dim fs As FileStream
' Delete the file if it exists.
If File.Exists(path) = False Then
' Create the file.
fs = File.Create(path)
Dim info As Byte() = New UTF8Encoding(True).GetBytes("This is some text in the file.")
' Add some information to the file.
fs.Write(info, 0, info.Length)
fs.Close()
End If
' Open the stream and read it back.
fs = File.Open(path, FileMode.Open, FileAccess.Read)
Dim b(1024) As Byte
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Do While fs.Read(b, 0, b.Length) > 0
Console.WriteLine(temp.GetString(b))
Loop
Try
' Try to get another handle to the same file.
Dim fs2 As FileStream = File.Open(path, FileMode.Open)
' Do some task here.
fs2.Close()
Catch e As Exception
Console.Write("Opening the file twice is disallowed.")
Console.WriteLine(", as expected: {0}", e.ToString())
End Try
fs.Close()
End Sub
End Class
Netcode
Veteran Poster
1,037 posts since Jun 2009
Reputation Points: 43
Solved Threads: 70
Skill Endorsements: 0
Did you replace the file path in line 7 with the file location on your system ?
Netcode
Veteran Poster
1,037 posts since Jun 2009
Reputation Points: 43
Solved Threads: 70
Skill Endorsements: 0
Are you creating X dynamicly during run time or is X a public variable that is created on form load?
Begginnerdev
Practically a Posting Shark
892 posts since Apr 2010
Reputation Points: 198
Solved Threads: 149
Skill Endorsements: 9
I just overlooked the last post of this thread and wanted to provide some code.clean up assistance. Hope it helps.:)
Imports System.IO
Public Class Form1
Private myStrings(0 To 4) As String
Private ofd As New OpenFileDialog, sfd As New SaveFileDialog
Private Sub _Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If ofd.ShowDialog = DialogResult.OK Then
myStrings = File.ReadAllLines(ofd.FileName)
TextBox1.Lines = myStrings
End If
End Sub
Private Sub _Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If sfd.ShowDialog = DialogResult.OK Then
Try
myStrings = TextBox1.Lines
File.WriteAllLines(sfd.FileName, myStrings)
Exit Sub
Catch ex As Exception
MsgBox("Woops. There was a problem saving.")
End Try
End If
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Button1.Text = ".save" : Button2.Text = ".load"
End Sub
End Class
codeorder
Postaholic
2,124 posts since Aug 2010
Reputation Points: 256
Solved Threads: 387
Skill Endorsements: 8