Hi.
I'm using Visual Studio 2005 so I didn't know where to put this topic.

This is my problem.

I made a qucik search program so when I browse for a text file, it adds that text file to a listbox1. And then when you search result will be placed in listbox2

Now I'm wondering how to force the program to automaticly load last opened text file on startup.

I tried with this and then I stuck.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim reader As IO.StreamReader = _
            New IO.StreamReader(winDir & "\system.ini")
        Try
            Me.ListBox1.Items.Clear()
            Do
                Me.ListBox1.Items.Add(reader.ReadLine)
            Loop Until reader.Peek = -1

        Catch
            Me.ListBox1.Items.Add("File is empty")

        Finally
            reader.Close()
        End Try
    End Sub

I don't even know if this is good.

You could save the last loaded file name in a text file or a My.Settings string variable at form close. To do it in My.Settings, go to your project properties and the Settings section. Define a new string value (this example uses the name LastLoadedFile). When the form loads you can

lastfile = My.Settings.LastLoadedFile

Before you load the file make sure it still exists. To save the file name on form close just reverse the assignment.

Edited 4 Years Ago by Reverend Jim: n/a

Comments
Good implementation....

Which part did your program stuck at ? You can set breakpoint so that you know which line goes wrong

This code won't load last opened text file and the error says

Error 2 Name 'winDir' is not declared. 738 33 Label Search

Ok, two ways to fix your problem.

First,

Dim reader As IO.StreamReader = _
New IO.StreamReader(System.Environment.GetEnvironmentVariable("Windir") & "\yourprogram.ini")

Second,

Dim windir as String = "C:\Windows\System32\"

then use that current line of yours

The reason behind is VB.NET does not understand what you mean by windir, so some steps must be done before to get win directory
More to read here http://www.beansoftware.com/NET-Tutorials/Environment-Variables.aspx

Edited 4 Years Ago by tungnk1993: n/a

Thx a lot, but that won't help me to load last opened text file.

Just save the lastloadfile name (path) to a variable such as

Dim lastFile as String = "...."

Then in form1_close event ( what your program does right before it closes), use StreamWriter to write into your .ini file

New IO.StreamReader(winDir & "\system.ini")

maybe I can make you some idea.
I also open my database from the last open.

I write my opened database when I open Last database, then when Load is the last opened.

Sorry my english not good.

you have inifile = system.ini
You load from read your system.ini
you should write your system.ini when you open your file you write it too

Dim sFIle As String
  sFIle = "'" & dlg.FileName & "'"
                WriteIniFile(winDir & "\system.ini", "YourCode", "YourFile", sFIle)
Module ModIni
    Private Declare Ansi Function GetPrivateProfileString _
 Lib "kernel32.dll" Alias "GetPrivateProfileStringA" _
       (ByVal lpApplicationName As String, _
       ByVal lpKeyName As String, ByVal lpDefault As String, _
       ByVal lpReturnedString As String, _
       ByVal nSize As Integer, ByVal lpFileName As String) _
       As Integer
    Private Declare Ansi Function WritePrivateProfileString _
           Lib "kernel32.dll" Alias "WritePrivateProfileStringA" _
           (ByVal lpApplicationName As String, _
           ByVal lpKeyName As String, ByVal lpString As String, _
           ByVal lpFileName As String) As Integer

   

    Function WriteIniFile(ByVal sIniFileName As String, ByVal sSection As String, ByVal sItem As String, ByVal Stext As String) As Boolean
        Dim i As Integer
        On Error GoTo sWriteIniFileError
        i = WritePrivateProfileString(sSection, sItem, Stext, sIniFileName)
        WriteIniFile = True
        Exit Function
sWriteIniFileError:
        WriteIniFile = False
    End Function
End Module

Here is code to write the last loaded file

Private Sub Form1_Close(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Close
        Dim writer As IO.StreamWriter = _
            New IO.StreamReader(winDir & "\system.ini")
        writer.WriteLine(lastloadfile)
        writer.close()
        
    End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim reader As IO.StreamReader = _
            New IO.StreamReader(winDir & "\system.ini")
        Try
            Me.ListBox1.Items.Clear()
            Do
                Me.ListBox1.Items.Add(reader.ReadLine)
            Loop Until reader.Peek = -1

        Catch
            Me.ListBox1.Items.Add("File is empty")

        Finally
            reader.Close()
        End Try
    End Sub

Edited 4 Years Ago by tungnk1993: n/a

Ok, since you are using visual studio, please take a look at the attachments. Double click on the formClosing event, then write your code into that part ( attachment), it will be the code which your program executes when it's about to close.

If you cant find where to show those events, click on your form ( window ), click on properties on right sidebar, then click on lightning bolt icon

Edited 4 Years Ago by tungnk1993: n/a

Attachments Capture.jpg 23.93 KB Capture1.jpg 5.96 KB

And now where to put this

Ok, two ways to fix your problem.

First,

Dim reader As IO.StreamReader = _
New IO.StreamReader(System.Environment.GetEnvironmentVariable("Windir") & "\yourprogram.ini")

Second,

Dim windir as String = "C:\Windows\System32\"

then use that current line of yours

The reason behind is VB.NET does not understand what you mean by windir, so some steps must be done before to get win directory
More to read here http://www.beansoftware.com/NET-Tutorials/Environment-Variables.aspx

Attachments ldk_program.jpg 55.62 KB

Which part do you store the path for the last opened file?
You have to store it in a variable when your program's working so that when your program's about to close, lastloadfile will be the path of the last opened file.

It's easier if you can show your whole program here :)

Which part do you store the path for the last opened file?
You have to store it in a variable when your program's working so that when your program's about to close, lastloadfile will be the path of the last opened file.

It's easier if you can show your whole program here :)

I rather show the whole program just to you. Not publicly :icon_redface:

If you use database then why u wasting your time by reading and writing textfiles...???

Simply save the path of the recent file into the database table when the file is about to close. Now when the program starts first checks for the database table and grab all the path from that table. Simple.....

If you use database then why u wasting your time by reading and writing textfiles...???

Simply save the path of the recent file into the database table when the file is about to close. Now when the program starts first checks for the database table and grab all the path from that table. Simple.....

This is a search program. It consists of two listbox and one textbox.

You simply load the text file and search it. All I want is to force this program to remember last open text file, so it can automaticly load it on next startup.

You can use registry.

1. First the application will search a subkey and its value. If it found then the value will be the last path.
2. If the program could not found the subkey then it will create it and set the value as the opend file path.
3. Now each time a file open u have to set the value of the key as the path of that file.


Now when ever the application start all of the above process done ...

Dim k As String = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", Nothing)
        If k = Nothing Then
            My.Computer.Registry.CurrentUser.CreateSubKey("LastOpend")
            My.Computer.Registry.SetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", "C:\abc.txt")' Here i give a static path C:\abc.txt. But u have to give the lastopen file path.... okey...
            MsgBox("Nothing")
        Else
            Dim readValue As String
            readValue = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", Nothing)
            MsgBox(readValue)
        End If

Edited 4 Years Ago by kingsonprisonic: n/a

You can use registry.

1. First the application will search a subkey and its value. If it found then the value will be the last path.
2. If the program could not found the subkey then it will create it and set the value as the opend file path.
3. Now each time a file open u have to set the value of the key as the path of that file.


Now when ever the application start all of the above process done ...

Dim k As String = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", Nothing)
        If k = Nothing Then
            My.Computer.Registry.CurrentUser.CreateSubKey("LastOpend")
            My.Computer.Registry.SetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", "C:\abc.txt")' Here i give a static path C:\abc.txt. But u have to give the lastopen file path.... okey...
            MsgBox("Nothing")
        Else
            Dim readValue As String
            readValue = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", Nothing)
            MsgBox(readValue)
        End If

This is nice, but when I started it just give me the message box with it's path and one more thing. I can not give specific path for the file because when someone else start this program he don't have that file.

I give all msgbox s for your understanding....

In if statement it gives Nothing becoz nothing is get from the registry for first time.

So u can delete the msgbox from there.

But in the else part the msgbox will return the path stored into the registry. So use it.. and open the file from the path. I just only use the msgbox for displaying the path. But u have to use it......

Understand?????

You know that it was a simple problem, and you expecting that we do your whole program. Any beginner can solve their problem with the help i provided. So don't waste others time. Becoz time is so important .. I give you my 2 hours and at last you say u give up.... That's not a good decision... So never waste others time......

No, no I don't expect from you whole program. I have 735 lines of code. And I stuck on the last part.

I used this for browsing text file

Dim streamer As IO.StreamReader
        OpenFileDialog1.ShowDialog()
        If OpenFileDialog1.FileName.Length > 0 Then
            TextBox1.Text = OpenFileDialog1.FileName
            streamer = IO.File.OpenText(TextBox1.Text)
            Dim mystring() As String = streamer.ReadToEnd.Split(vbNewLine)
            ListBox1.Items.AddRange(mystring)
        End If
        TextBox1.Text = ""

But I can not use that for loading last opened file. I can not specify the path because it won't be always the same path.

Or maybe I'm making a mistake because it should be loaded in the listbox :?:

And if u want to load the file at runtime just add a an extra lin..

RcentToolStripMenuItem_Click(RcentToolStripMenuItem, e)

_________________________________________________________

Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim k As String = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", Nothing)
        If k = Nothing Then
            My.Computer.Registry.CurrentUser.CreateSubKey("LastOpend")
            My.Computer.Registry.SetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", "C:\abc.txt")
            'MsgBox("Nothing")
        Else
            Dim readValue As String
            readValue = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", Nothing)
            'MsgBox(readValue)
            RcentToolStripMenuItem.Text = readValue
            RcentToolStripMenuItem_Click(RcentToolStripMenuItem, e)
        End If

    End Sub

    Private Sub RcentToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RcentToolStripMenuItem.Click
        Dim sr As New System.IO.StreamReader(RcentToolStripMenuItem.Text)
        Me.TextBox1.Text = sr.ReadToEnd
        sr.Dispose()
    End Sub

    Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
        opn.ShowDialog()
        Try
            Dim sr As New System.IO.StreamReader(opn.FileName)
            Me.TextBox1.Text = sr.ReadToEnd
            sr.Dispose()
            My.Computer.Registry.CurrentUser.CreateSubKey("LastOpend")
            My.Computer.Registry.SetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", opn.FileName)


        Catch ex As Exception

        End Try
    End Sub

  
End Class
Comments
Thx

In probably its simplest form see the attached project zip. The code is

Public Class Form1

    Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        My.Settings.LastFile = txtFileName.Text

    End Sub

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        txtFileName.Text = My.Settings.LastFile

        If My.Computer.FileSystem.FileExists(txtFileName.Text) Then
            txtFileContents.Text = My.Computer.FileSystem.ReadAllText(txtFileName.Text)
        End If

    End Sub

    Private Sub btnLoadFile_Click(sender As System.Object, e As System.EventArgs) Handles btnLoadFile.Click

        If My.Computer.FileSystem.FileExists(txtFileName.Text) Then
            txtFileContents.Text = My.Computer.FileSystem.ReadAllText(txtFileName.Text)
        End If

    End Sub

End Class

What does this code in form load really do?

I used your code for Recent Files but I change it a little because I need it to load a text file to listbox

So I put this

Private Sub RcentToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RcentToolStripMenuItem.Click
        Dim sr As New System.IO.StreamReader(RcentToolStripMenuItem.Text)
        Do Until sr.EndOfStream
            Me.ListBox1.Items.Add(sr.ReadLine())'changed line 
        Loop
    End Sub
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
 
    'get the name of the last loaded file from Settings and copy it to the textbox

    txtFileName.Text = My.Settings.LastFile
 
    'if the file exists then copy the file contents to the multi-line text box

    If My.Computer.FileSystem.FileExists(txtFileName.Text) Then
        txtFileContents.Text = My.Computer.FileSystem.ReadAllText(txtFileName.Text)
    End If
 
End Sub

What should I change here to make it works

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim k As String = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", Nothing)
        If k = Nothing Then
            My.Computer.Registry.CurrentUser.CreateSubKey("LastOpend")
            My.Computer.Registry.SetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", "C:\abc.txt")
            'MsgBox("Nothing")
        Else
            Dim readValue As String
            readValue = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\LastOpend", "LastOpend", Nothing)
            'MsgBox(readValue)
            RcentToolStripMenuItem.Text = readValue
        End If
    End Sub
This article has been dead for over six months. Start a new discussion instead.