【问题标题】:How do you store strings in a .txt file?如何将字符串存储在 .txt 文件中?
【发布时间】:2015-11-21 06:17:58
【问题描述】:

过去几天我一直在创建一个程序。该程序存储了一个字符串“Dim info As String = Nothing”,稍后会在其中询问输入。

EG:我输入“Hello World!”对于变量“info”,如何将“info”(Hello World!)的值存储到 .txt 文件中?或者这不可能?

(仍然是 vb.net 的初学者,正在寻找简单的答案。)

尝试1(请找出错误):

Sub Main()
    Dim path As String = "C:\VBTextFiles\Test1.txt"
    Dim stringex As String = "Hello world!"
    File.WriteAllText(path, stringex)
End Sub

【问题讨论】:

标签: vb.net visual-studio-2012


【解决方案1】:

您可以使用IO.File.WriteAllText 创建一个文件并将您的info 写入其中。

This pageCreateAppend 的示例。这是 Create 的相关部分:

Dim path As String = "c:\temp\MyTest.txt" 
' This text is added only once to the file. 
If File.Exists(path) = False Then 
  ' Create a file to write to. 
  Dim createText As String = "Hello and Welcome" + Environment.NewLine
  File.WriteAllText(path, createText)
End If 

对于 APPEND,请使用 AppendAllText。见Example

【讨论】:

  • 我需要先创建文件吗?或者它会为我创造它吗?如果我只是为路径写了'MyTest.txt',它会将它保存在......?还是我必须写整个路径?
  • @Meraj99: WriteAllText 将为您创建文件。它应该接受任何有效的路径。如果你指定一个短路径,应该保存在Environment.CurrentDirectory(你可以用调试器检查它指向的位置)。
  • 错误 BC30451:未声明“文件”。由于其保护级别,它可能无法访问。
  • @Meraj99:改用IO.File。命名空间应该是完全限定的,除非您在代码文件的顶部导入其中的一部分。
  • 嗯,我只是创建了一个“控制台 Win32 应用程序”。并在子部分中执行代码。
【解决方案2】:
Dim path As String = "c:\temp\MyTest.txt" 
' This text is added only once to the file. 
If File.Exists(path) = True Then 
  ' Create a file to write to. 
  Dim createText As String = "Hello and Welcome" + Environment.NewLine
  File.WriteAllText(path, createText)
End If 

在第 3 行将 False 更改为 True :)

【讨论】:

  • 这样会不会更简单If File.Exists(path) Then
猜你喜欢
  • 2021-02-09
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
相关资源
最近更新 更多