【问题标题】:Add a path to a code VB.net / visual basic添加代码路径 VB.net / visual basic
【发布时间】:2020-10-29 18:33:59
【问题描述】:

如何向“HERE_HAS_TO_BE_A_PATH”所在的代码添加路径。当我这样做时,我收到一条错误消息。目标是能够指定保存最终文本文件的路径。 谢谢!

这是一个代码:

    Dim newFile As IO.StreamWriter = IO.File.CreateText("HERE_HAS_TO_BE_A_PATH")
    Dim fix As String
    fix = My.Computer.FileSystem.ReadAllText("C:\test.txt")
    fix = Replace(fix, ",", ".")
    My.Computer.FileSystem.WriteAllText("C:\test.txt", fix, False)


    Dim query = From data In IO.File.ReadAllLines("C:\test.txt")
                Let name As String = data.Split(" ")(0)
                Let x As Decimal = data.Split(" ")(1)
                Let y As Decimal = data.Split(" ")(2)
                Let z As Decimal = data.Split(" ")(3)
                Select name & " " & x & "," & y & "," & z


    For i As Integer = 0 To query.Count - 1
        newFile.WriteLine(query(i))
    Next

    newFile.Close()

【问题讨论】:

  • 错误信息是什么意思?
  • File.WriteAllLines(path, query) 会做到的。此外,如果您写入不同的文件,请使用ReadLines 而不是ReadAllLines。前者在枚举行时读取行,而不将它们存储在数组中。
  • 错误信息显示:“System.UnauthorizedAccessException: 'Access to the path 'C:\test.xyz' is denied.'” 当我将路径更改为 C:\test\test.xyz它有效您的建议是否适合我的代码的第一行?看起来你的意思是不同的行
  • 我认为根目录 `C:` 是为 Windows 的系统内容保留的,可能访问受限。

标签: vb.net path


【解决方案1】:

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

【讨论】:

  • 流应该在Using 块中。他们需要处理
  • 好主意,我把它放在后面的部分以避免一次与太多更改混淆
【解决方案2】:

你可以这样写。流编写器会自动创建文件。

 Dim newFile As New StreamWriter(HERE_HAS_TO_BE_A_PATH)

PS:我不能在评论部分提及所有这些,因为我的声誉低于 50,所以我写了我的答案。如有错误请随时告诉我

问候, vikyath

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2015-12-03
    • 2016-07-07
    相关资源
    最近更新 更多