单字符字符串无法正确写入文件

时间:2015-04-21 09:44:32

标签: vb.net file-io

我的代码出现问题,我会把我的数组内容写成文件,如下所示: -

Private Sub DumpArray (ByRef array_to_dump(,) As MyEnum, ByVal file_name As String)

    Dim sw As StreamWriter = New StreamWriter(file_name)

    For i As Integer = array_to_dump.GetLowerBound(0) To array_to_dump.GetUpperBound(0)

        For j As Integer = array_to_dump.GetLowerBound(1) To array_to_dump.GetUpperBound(1)

            If array_to_dump(i, j) = MyEnum.This Then
                sw.Write("Fred")
            Else
                sw.Write("Bert")
            End If

            sw.Write(vbTab)

        Next j

        sw.WriteLine

    Next i

    sw.Flush
    sw.Close

End Sub

这产生了我期望的输出;在当前情况下,文件填充" Fred",由制表符分隔。但是,如果我将代码的业务结束更改为: -

            If array_to_dump(i, j) = MyEnum.This Then
                sw.Write("1")
            Else
                sw.Write("0")
            End If

文件中填充了非打印字符,这些字符在记事本中显示为小方块,而不是" 0"由我期待的标签分隔。任何其他单字符串对都是一样的。

虽然这不是一个迫切的重要问题,但我对于为什么会这样,我很好奇。有谁知道吗?

2 个答案:

答案 0 :(得分:1)

当您声明SteamWriter之类的@DavidSdot时,您必须将encoding设置为其他内容。像这样:

Dim writer As StreamWriter = New StreamWriter(file_name, Encoding.Default)

乱搞那个属性,你可能会发现一个很好的价值。我不是编码方面的专家,但这应该是你问题的罪魁祸首。

答案 1 :(得分:1)

我尝试重现问题,但下面的代码工作正常。将它与您的真实代码进行比较...也许原版中有拼写错误或其他内容?

Option Strict On
Imports System.IO

Public Class Form1
  Private Enum MyEnum As Integer
    This
    That
  End Enum

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim myArray(1, 1) As MyEnum
    myArray(0, 0) = MyEnum.This
    myArray(0, 1) = MyEnum.This
    myArray(1, 0) = MyEnum.This
    myArray(1, 1) = MyEnum.That

    Call DumpArray(myArray, "C:\Junk\Junk.txt")
  End Sub

  Private Sub DumpArray(ByRef array_to_dump(,) As MyEnum, ByVal file_name As String)

    Dim sw As StreamWriter = New StreamWriter(file_name)
    For i As Integer = array_to_dump.GetLowerBound(0) To array_to_dump.GetUpperBound(0)
      For j As Integer = array_to_dump.GetLowerBound(1) To array_to_dump.GetUpperBound(1)
        If array_to_dump(i, j) = MyEnum.This Then
          sw.Write("0")
        Else
          sw.Write("1")
        End If
        sw.Write(vbTab)
      Next j
      sw.WriteLine()
    Next i
    sw.Flush()
    sw.Close()
  End Sub
End Class