简体   繁体   中英

VB.Net Read txt file from current directory

How can I get the application current directory and read the file from here? So the application is in the same folder as the Logger.txt but when I start the app its try to read from the root folder of the application. Logger.txt is in the Logging/MainObject/Logger.txt I have tryed to add the CurrentDirectory thing, but its gives me error,so I added bad.

 Dim sr As New StreamReader("Logger.txt")
 Dim line As String
 line = sr.ReadToEnd()

First of all I think you're confused about the difference between "Current directory" and "application directory". The current directory is piece of information maintained by the process to track what directory you're currently working in, so when you refer to a file without specifying a full path, it knows where to look for that file. The application directory is where the application's EXE file resides on the file system. Since reading from the current directory is a simple matter of referring to the file without providing a full path, I assume what you're trying to do is read a file from the application's directory (where the EXE file resides). Here's code to do that:

Dim ApplicationDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Dim LogfilePath = System.IO.Path.Combine(ApplicationDir, "Logger.txt")
Using sr As New System.IO.StreamReader(LogfilePath)
    sr.ReadToEnd()
End Using

Use Application.StartupPath

Dim sr As New StreamReader(Application.StartupPath & "\Logger.txt")
Dim line As String
line = sr.ReadToEnd()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM