【问题标题】:Trying to create a good path in vb.net试图在 vb.net 中创建一个好的路径
【发布时间】:2013-12-13 22:35:57
【问题描述】:

我正在编写一个创建一些文本文件的应用程序。我希望它们在一些文件夹中,所以我这样做了:

Dim fileLoc As String = "c:\users\%username%\downloads\users.txt"
    If 1 + 1 = 2 Then <--- not very professional but it works! it works....
        Dim fs As FileStream = Nothing
        If (Not File.Exists(fileLoc)) Then
            fs = File.Create(fileLoc)
            Using fs
            End Using
        End If
    End If
    If File.Exists(fileLoc) Then
        Using sw As StreamWriter = New StreamWriter(fileLoc)
            sw.Write(pcname.Text)
        End Using
    End If

但是当我尝试调试时,会发生以下情况:

DirectoryNotFoundException 未处理 找不到部分路径(c:\users\%username%\downloads\users.txt)

我确定这是因为“%username%”,因为当我填写整个路径时,它可以工作。 但是当程序在另一台电脑上时它就不能工作了!

【问题讨论】:

  • 你有用户名吗?
  • 出于好奇 - 为什么是If 1 + 1 = 2
  • lol 也许可以忽略 1+1 = 2(它总是等于 true)并删除 if 语句(以节省更多代码行!)。
  • 这是因为我想在 form_load 中运行它,而不是在有人开始操作时运行它

标签: vb.net appdata


【解决方案1】:

尝试这样的事情

Dim userName as string = WindowsIdentity.GetCurrent().Name;

Dim fileLoc As String = "c:\users\" & userName & "\downloads\users.txt"
    If 1 + 1 = 2 Then <--- not very professional but it works! it works....
        Dim fs As FileStream = Nothing
        If (Not File.Exists(fileLoc)) Then
            fs = File.Create(fileLoc)
            Using fs
            End Using
        End If
    End If
    If File.Exists(fileLoc) Then
        Using sw As StreamWriter = New StreamWriter(fileLoc)
            sw.Write(pcname.Text)
        End Using
    End If

【讨论】:

    【解决方案2】:

    我认为你不能像这样使用环境变量。

    相反

    Dim fileLoc As String = "c:\users\%username%\downloads\users.txt"
    

    试试

    Dim fileLoc As String = "c:\users\" & Environment.UserName & "\downloads\users.txt"
    

    【讨论】:

    • 使用Dim fileLoc As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "downloads\users.txt")会更安全。
    • 很高兴它有帮助。如果解决方案有用,请标记为已回答。
    【解决方案3】:
    Dim fileLoc As String = "c:\users\" & Environment.UserName & "\downloads\users.txt"
    If 1 + 1 = 2 Then <--- not very professional but it works! it works....
        Dim fs As FileStream = Nothing
        If (Not File.Exists(fileLoc)) Then
            fs = File.Create(fileLoc)
            Using fs
            End Using
        End If
    End If
    If File.Exists(fileLoc) Then
        Using sw As StreamWriter = New StreamWriter(fileLoc)
            sw.Write(pcname.Text)
        End Using
    End If
    

    这是正确的代码!谢谢大家和我一起思考!

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 2016-07-21
      • 2017-08-07
      相关资源
      最近更新 更多