我正在创建一个将在几台计算机上使用的刽子手游戏,我已经创建了刽子手游戏本身,但我正在使用"加载形式"程序首次启动时创建列表的功能,但我遇到了这个问题。
未处理的类型' System.IO.IOException'发生在mscorlib.dll中 附加信息:该过程无法访问文件' h:\ Bryson \ words.txt'因为它正被另一个进程使用。
Using sw As StreamWriter = File.CreateText("h:\Bryson\words.txt")
^^该行是错误弹出的地方^^
我在代码中添加了一些注释,以使生活更轻松。如果有人可以提前帮助谢谢:)
'USED TO CREATE HANGMAN FILE IF NOT FOUND
Private Sub main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
fofound = False
fifound = False
MsgBox("remove this and change file path and fix qu2 quiz")
'DESIGNER USE
Dim path As String = "h:\Bryson\words.txt"
'CREATE VAR FOR PATH
If System.IO.Directory.Exists("h:\Bryson") Then
'CHECKS IF FOLDER EXISTS
fofound = True
Else
'IF IT DOES THEN IT MOVES ON
System.IO.Directory.CreateDirectory("h:\Bryson")
'IF NOT IT CREATES THE FOLDER
fofound = True
If File.Exists("h:\Bryson\test\words.txt") Then
'CHECKS IF FILE EXISTS
fifound = True
Else
'IF IT DOES IT MOVES ON
IO.File.Create("h:\Bryson\words.txt")
'IF NOT IT CREATES IT
FileClose()
End If
End If
If fofound And fifound = True Then
Else
Using sw As StreamWriter = File.CreateText("h:\Bryson\words.txt")
'CRASH POINT The process cannot access the file 'C:\Bryson\words.txt'
'because it Is being used by another process.
sw.WriteLine("Hangman")
sw.WriteLine("computer")
sw.WriteLine("electrode")
sw.WriteLine("independent")
sw.WriteLine("stream")
sw.WriteLine("enforcing")
End Using
'WRITES TO FILE
MsgBox("file created")
'DESIGNER USE
FileClose()
'CLOSES FILE
End If
End Sub
答案 0 :(得分:0)
FileClose()
是VB6的遗留函数,不会影响System.IO
命名空间中的任何内容。要关闭文件,您需要在已打开文件的流上调用.Close()
或.Dispose()
(将流包装在Using
块中会自动执行此操作。
你的问题就在这一行:
IO.File.Create("h:\Bryson\words.txt")
该方法创建一个新文件并打开一个FileStream
来锁定文件。由于您从未关闭返回的FileStream
,因此在关闭应用程序之前,您的文件将保持锁定状态。
File.Create()
调用完全没有必要,因为如果文件不存在,File.CreateText()
会创建文件。所以你应该删除上面一行。