我搜索了不同的解决方案,以帮助我调试我的程序,但没有任何工作。我正在创建一个项目生成器,它生成项目和统计信息,然后创建并写入.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次,所以如果我可以将第一个代码修复,我可以将其应用到其余代码中。
答案 0 :(得分:3)
正如评论中所解释的那样,需要关闭流并将其处理以将其内部缓冲区刷新到磁盘。您可以希望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
当代码到达结束时使用编译器添加所需的代码以在此代码的开头处废弃在using块内创建的一次性对象。通过这种方式,您可以释放资源(文件句柄),一切都应该顺利进行。