VB.Net 从当前目录读取txt文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38291345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.Net Read txt file from current directory
提问by Richárd Kiss
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.
如何获取应用程序当前目录并从此处读取文件?因此该应用程序与 Logger.txt 位于同一文件夹中,但是当我启动该应用程序时,它会尝试从该应用程序的根文件夹中读取数据。Logger.txt 在 Logging/MainObject/Logger.txt 中,我尝试添加 CurrentDirectory 内容,但它给了我错误,所以我添加了错误。
Dim sr As New StreamReader("Logger.txt")
Dim line As String
line = sr.ReadToEnd()
回答by BlueMonkMN
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:
首先,我认为您对“当前目录”和“应用程序目录”之间的区别感到困惑。当前目录是由进程维护的一条信息,用于跟踪您当前在哪个目录中工作,因此当您在未指定完整路径的情况下引用文件时,它知道在哪里查找该文件。应用程序目录是应用程序的 EXE 文件驻留在文件系统上的位置。由于从当前目录读取是在不提供完整路径的情况下引用文件的简单问题,因此我假设您尝试做的是从应用程序目录(EXE 文件所在的目录)读取文件。这是执行此操作的代码:
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
回答by F0r3v3r-A-N00b
Use Application.StartupPath
使用 Application.StartupPath
Dim sr As New StreamReader(Application.StartupPath & "\Logger.txt")
Dim line As String
line = sr.ReadToEnd()

