【问题标题】:VB.Net Writing to created text file not working System.IOVB.Net 写入创建的文本文件不起作用 System.IO
【发布时间】:2017-03-09 22:20:02
【问题描述】:

我已经搜索了不同的解决方案来帮助我调试我的程序,但没有任何效果。我正在创建一个项目生成器,它生成项目和统计信息,然后创建并写入 .txt 文件。唯一的问题是它没有写入文本文件,我不知道为什么。 下面是创建和写入文件的代码:

                'Creates item text file
                TextName = "Item" & ItemCount & "." & ItemType & ".Level" &        Level & "." & itemClass & "." & Rarity(0)
                Dim path As String = "C:\Users\ryanl3\Desktop\My Stuff\Realms\Items\" & TextName & ".txt"

                'Appends the stats to text file
                Dim fw As System.IO.StreamWriter
                fw = File.CreateText(path)
                fw.WriteLine("Name: " & itemName)
                fw.WriteLine("Type: " & ItemType)
                fw.WriteLine("Damage: " & itemDamage)
                fw.WriteLine("Class: " & itemClass)
                fw.WriteLine("Rarity: " & Rarity(0))

我知道统计信息生成代码正在工作,因为其中一些存储在文本文件名中。这段代码在整个源代码中至少重复了 20 次,所以如果我能修复第一个代码块,我可以将它应用到其余部分。

【问题讨论】:

  • 你关闭了那个streamwriter吗?对了,开始使用 using 语句
  • 文件流有一个缓冲区——它不会逐行或逐个字符地写入。当您关闭并处理流时,它将刷新缓冲区。

标签: vb.net filestream system.io.file


【解决方案1】:

如 cmets 中所述,需要关闭并处理流以使其内部缓冲区刷新到磁盘。您可以希望 StreamWriter 超出范围,然后垃圾收集器会为您关闭它,但在可靠的应用程序中,您应该自己处理这个问题。

using statement 非常适合这种情况

    Using fw = File.CreateText(path)
       fw.WriteLine("Name: " & itemName)
       fw.WriteLine("Type: " & ItemType)
       fw.WriteLine("Damage: " & itemDamage)
       fw.WriteLine("Class: " & itemClass)
       fw.WriteLine("Rarity: " & Rarity(0))
   End Using

当代码到达 End Using 时,编译器添加所需的代码以 Dispose 在此代码开头的 using 块中创建的一次性对象。这样你就释放了资源(文件句柄),一切都应该顺利进行。

【讨论】:

  • 我已经用这个替换了所有的源代码块,一旦生成.txt文件我会告诉你它是否可以工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-13
  • 2021-10-04
相关资源
最近更新 更多