Problem opening and saving text files.
Okay so I have created a script that should open and save text files according to the date which has been selected on a datetimepicker control.
In my Bin\Debug directory I have a text file named "30 December 2007.txt"
and here is my code:
vb Code:
Imports System.IO
Public Class Form1
Dim SR As StreamReader
Dim SW As StreamWriter
Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged
Dim theDatePicked As String = DateTimePicker1.Text & ".txt"
SR = New StreamReader(theDatePicked)
TextBox1.Text = SR.ReadToEnd
End Sub
Private Sub Button16_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button16.Click
Dim theDatePicked As String = DateTimePicker1.Text & ".txt"
SW = New StreamWriter(theDatePicked)
SW.Write(TextBox1.Text)
SW.Flush()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim theDatePicked As String = DateTimePicker1.Text & ".txt"
SR = New StreamReader(theDatePicked)
TextBox1.Text = SR.ReadToEnd
End Sub
End Class
I keep getting this error message when I try to debug it.
Quote:
An error occurred creating the form. See Exception.InnerException for details. The error is: Could not find file 'C:\Users\Matt's Computer\Documents\Visual Studio 2008\Projects\iDiary\iDiary\bin\Debug\.txt'.
Re: Problem opening and saving text files.
You have this:
Dim theDatePicked As String = DateTimePicker1.Text & ".txt"
Try this:
Dim theDatePicked As String = DateTimePicker1.Value & ".txt"
Re: Problem opening and saving text files.
I strongly suggest that if you want to name files by date that you use a sortable format, so that chronological order matches alphabetical order. I also strongly suggest that you close your files after using them. Assuming that you're using VB 2005 this is all very simple:
vb.net Code:
Me.TextBox1.Text = IO.File.ReadAllText(IO.Path.Combine(Application.StartupPath, _
String.Format("{0:yyyyMMdd}.txt", _
Me.DateTimePicker1.Value)))
vb.net Code:
IO.File.WriteAllText(IO.Path.Combine(Application.StartupPath, _
String.Format("{0:yyyyMMdd}.txt", _
Me.DateTimePicker1.Value)), _
Me.TextBox1.Text)