【问题标题】:Hangman System.IO.IOException' occurred in mscorlib.dll刽子手 System.IO.IOException' 在 mscorlib.dll 中发生
【发布时间】:2017-03-31 01:42:50
【问题描述】:

我正在创建一个要在几台计算机上使用的刽子手游戏,我已经创建了刽子手游戏本身,但我正在使用“加载表单”功能在程序首次启动时创建列表,但我有这个问题。

在 mscorlib.dll 中出现“System.IO.IOException”类型的未处理异常 附加信息:该进程无法访问文件“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

【问题讨论】:

  • 刚刚运行你的代码,它似乎工作。但是,请检查您是否有 drive H: ,我认为您没有并修复您的路径。它应该类似于 C:\Bryson\words.txt 而不是 h:\Bryson\words.txt
  • @3vts 是的,有一个 H 驱动器,我已经确认了。我所有的文件都在 H 盘上
  • 您的变量fifound永远为真。您仅在创建新文件夹时检查文件是否存在。由于您刚刚创建了新文件夹,因此不可能存在文件,因此 fifound 将始终为 false。此外,有一个空的 If 块是一种代码气味。我会删除 Else 并将 If 更改为 If Not (fofound AndAlso fifound) Then

标签: vb.net


【解决方案1】:

FileClose() 是 VB6 的遗留函数,不会影响 System.IO 命名空间中的任何内容。要关闭文件,您需要在打开文件的流上调用.Close().Dispose()(将流包装在Using 块中会自动执行此操作)。

你的问题是这一行:

IO.File.Create("h:\Bryson\words.txt")

该方法创建一个新文件并打开一个FileStream 锁定文件。由于您从未关闭返回的FileStream,因此您的文件将保持锁定状态,直到您关闭应用程序。

File.Create() 调用完全没有必要,因为如果文件不存在,File.CreateText() 将创建该文件。所以你应该删除上面的行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-20
    • 2015-07-18
    • 2018-10-20
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 2017-03-09
    相关资源
    最近更新 更多