1) 使用文字字符串:
最简单的方法是将“HERE_HAS_TO_BE_A_PATH”替换为所需输出目标的文字路径,因此用“C:\output.txt”覆盖它:
Dim newFile As IO.StreamWriter = IO.File.CreateText("C:\output.txt")
2) 检查权限和读/写文件引用是否正确:
您可能遇到困难的原因有几个,如果您尝试读取和写入根 C:\ 目录,您可能会遇到权限问题。
此外,请逐行确保每次使用其中一个或另一个时输入和输出文件都是正确的。
3) 确保隐式路径对于非完全限定路径是正确的:
接下来,当您测试运行程序时,它实际上与项目文件夹不在同一个文件夹中,如果您使用相对路径,它位于子文件夹“\bin\debug”中,因此对于名为[ProjectName],默认编译到这个文件夹:
C:\path\to\[ProjectName]\bin\Debug\Program.exe
换句话说,如果您尝试输入路径名作为字符串来保存文件,并且您没有指定从 C:\ 驱动器开始的完整路径名,例如“output.txt” “C:\output.txt”,它保存在这里:
C:\path\to\[ProjectName]\bin\Debug\output.txt
要准确了解它默认的路径,在 .Net Framework 中,您可以检查这些:
Application.ExecutablePath
Application.StartupPath
4) 通过 SaveFileDialogue 获取用户输入
如果您希望用户提供输入,除了文字字符串(“C:\output.txt”)之外,因为看起来您正在使用 .Net Framework(而不是 .Net Core 等) ,设置要在程序中使用的文件名的最简单方法是使用 System.Windows.Forms 中的内置 SaveFileDialogue 对象(就像您尝试使用大多数程序保存文件时看到的那样),您可以非常快速地做到这一点像这样:
Dim SFD As New SaveFileDialog
SFD.Filter = "Text Files|*.txt"
SFD.ShowDialog()
' For reuse, storing file path to string
Dim myFilePath As String = SFD.FileName
Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' path var
' Do the rest of your code here
newFile.Close()
5) 通过控制台获取用户输入
如果您想在 .Net Core 中获取路径,即使用控制台,主进程默认接受名为 args() 的字符串数组,这是一个不同的版本,允许用户添加路径作为第一个运行程序时的参数,或者如果没有提供参数,它会要求用户输入:
Console.WriteLine("Hello World!")
Dim myFilePath = ""
If args.Length > 0 Then
myFilePath = args(0)
End If
If myFilePath = "" Then
Console.WriteLine("No file name provided, please input file name:")
While (myFilePath = "")
Console.Write("File and Path: ")
myFilePath = Console.ReadLine()
End While
End If
Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' path var
' Do the rest of your code here
newFile.Close()
6) 最佳实践:关闭和处置与使用块
为了使代码尽可能与您的相似,我尝试只更改需要更改的部分。 Vikyath Rao 和 Mary 分别指出了一种简化的声明方式以及常见的最佳实践。
有关更多信息,请查看以下有用的说明:
Can any one explain why StreamWriter is an Unmanaged Resource. 和
Should I call Close() or Dispose() for stream objects?
总而言之,虽然流是托管的并且应该自动收集垃圾,但由于使用文件系统涉及非托管资源,这就是手动处置对象是个好主意的主要原因。您的“.close()”会执行此操作。 StreamReader 和 StreamWriter 类的重写调用“.dispose()”方法,但是使用 Using .. End Using 块以避免“用剪刀运行”仍然是常见的做法,因为 Enigmativity 提出它在他的帖子中,换句话说,它确保您不会在程序的其他地方离开而忘记处理打开的文件流。
在您的程序中,您可以简单地将 "Dim newFile As IO.StreamWriter = IO.File.CreateText("C:\output.txt")" 和 "newFile.close()" 行替换为开始和结束使用简化语法时使用块的语句,如下所示:
'Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' old
Using newFile As New IO.StreamWriter(myFilePath) ' new
Dim fix As String = "Text from somewhere!"
newFile.WriteLine(fix)
' other similar operations here
End Using ' new -- ensures disposal
'newFile.Close() ' old