如何在VB.NET中将多个Double类型变量的值以竖线分隔写入.txt文件的同一行?
Got it, the issue here is that you're writing literal strings instead of referencing your actual V1, V2, V3 variables. Let's fix this with a few clean, reliable approaches—plus I'll throw in a best practice for file handling to avoid headaches later.
First, the Core Fix: Reference Your Variables
Instead of hardcoding "The Value of V1", you need to use the variables themselves. VB.NET will automatically convert Double values to strings when concatenating, but you can also explicitly format them if you need control over decimal places, etc.
Option 1: String Concatenation (Straightforward)
' First, make sure your variables are initialized with values! Dim V1 As Double = 15.67 Dim V2 As Double = 89.01 Dim V3 As Double = 42.34 ' Use Using statement to auto-close the file (safer than manual Close()) Using file As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("test.txt", True) file.WriteLine(V1 & "|" & V2 & "|" & V3) End Using
Option 2: String.Format (Cleaner for Multiple Values)
This makes the structure easier to read, especially if you add formatting later:
Dim V1 As Double = 15.67 Dim V2 As Double = 89.01 Dim V3 As Double = 42.34 Using file As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("test.txt", True) file.WriteLine(String.Format("{0}|{1}|{2}", V1, V2, V3)) End Using
Option 3: String Interpolation (Modern VB.NET)
If you're using Visual Studio 2015 or later, interpolation is the most intuitive way:
Dim V1 As Double = 15.67 Dim V2 As Double = 89.01 Dim V3 As Double = 42.34 Using file As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("test.txt", True) file.WriteLine($"{V1}|{V2}|{V3}") End Using
Bonus: Control Number Formatting
If you need to specify decimal places (e.g., 2 decimal places), modify the variable references like this:
- Concatenation:
V1.ToString("F2") - String.Format:
"{0:F2}|{1:F2}|{2:F2}" - Interpolation:
$"{V1:F2}|{V2:F2}|{V3:F2}"
Why Use Using?
The Using statement automatically disposes of the StreamWriter when it's done, even if an error occurs. This avoids leaving the file locked or unclosed, which is a common pitfall with manual Close() calls.
内容的提问来源于stack exchange,提问作者Alex

