Sunday, August 2, 2009

Application.StartupPath (VB--Visual Studio 2005)?

I have a program (my first where I made up all the code instead of copying it out of a learn-to-program book!) that needs to use a .txt file as input. I've been using the line:





FileOpen(1, "C:\Folder Name\FileName.txt", OpenMode.Input)





but I wanted to change the hard coded path to use Application.StartupPath instead so that if people put it somewhere other than the C drive it would still work. So I used the line:





FileOpen(1, Application.StartupPath %26amp; "\Folder Name\FileName.txt", OpenMode.Input)





but then my code wouldn't debug properly.





I get an error message when I try to debug that says:


Could not find a part of the path 'C:\Folder Name\Folder Name\Folder Name\bin\Release\Folder Name\FileName.txt'.





What am I doing wrong?





Thanks!

Application.StartupPath (VB--Visual Studio 2005)?
Not a simple problem. You do nothing wrong. Windows (more exactly - VB) does some unclear things.


"Working directory", as Microsoft thinks, is sometimes directory of "current user home directory", sometimes "c:\", depending on what buggy Windows version you use.


You need to use GetModuleFileName funcrion from Win32 API to obtain full pathname of your executable. Then you need to strip filename (after last backslash) - and you will get current directory where your program is placed.
Reply:Make a button n write this lil code....





Dim ofd As New OpenFileDialog()


Dim dia_result As DialogResult = ofd.ShowDialog()


If dia_result %26lt;%26gt; DialogResult.Cancel Then


Dim fstream As New FileStream(ofd.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)


Dim sw As StreamReader = New StreamReader(fstream)


Dim temp As String = sw.ReadToEnd()


'write the file to a TextBox1


TextBox1.Text=temp





end if


No comments:

Post a Comment