为什么 File.Open() 打不开文件?

Why does File.Open() not open the file?

我正在 VB.NET Windows Forms 应用程序中实现“保存文件”按钮。

我正在尝试封装 Windows 应用程序中保存按钮的正常预期行为。 I.E:如果已经选择了一个文件,则打开当前文件,写入并保存; else 如果没有当前文件,或者使用了另存为,则显示一个SaveFileDialog,然后打开,写入和保存。

我目前已经编写了以下函数,但我一直收到异常:

Cannot access a closed file

文件创建得很好,但是是空的(它应该包含 "Test string")。我不明白文件是如何关闭的,除非某种垃圾收集以某种方式消除它??

当前代码:

Function SaveFile(ByVal Type As ProfileType, ByVal suggestedFileName As String, ByVal saveAs As Boolean, ByVal writeData As String) As Boolean
    Dim FileStream As Stream = Nothing
    Dim FolderPath As String = Nothing
    Dim CancelSave As Boolean = False
    Dim SaveFileDialog As SaveFileDialog = New SaveFileDialog()

    Try
        If Type = ProfileType.Product Then 'Select the initial directory path
            FolderPath = ProductPath
        Else
            FolderPath = ProfilePath
        End If

        If (FileName = String.Empty Or saveAs = True) Then 'If a file is not already selected launch a dialog to allow the user to select one
            With SaveFileDialog
                .Title = "Save"
                .AddExtension = True
                .CheckPathExists = True
                .CreatePrompt = False
                .DefaultExt = "xml"
                .Filter = "Xml Files (*.xml)|*.xml"
                .FilterIndex = 0
                .FileName = suggestedFileName
                .InitialDirectory = FolderPath
                If .ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                    FullyQualfiedPathName = New String(SaveFileDialog.FileName) 'Save the path and name of the file
                    FileName = Path.GetFileName(FullyQualfiedPathName)
                Else
                    CancelSave = True
                End If
                .Dispose()
            End With
        End If

        If (FileName <> String.Empty) Then 'Write the string to the file if the filewas correctly selected
            FileStream = File.Open(FullyQualfiedPathName, FileMode.OpenOrCreate, FileAccess.ReadWrite) 'Open the file
            Using FileStreamWriter As New StreamWriter(FileStream) 'Create the stream writer
                FileStreamWriter.Write(writeData) 'Write the data
                FileStream.Close() 'Clse the file
            End Using
        ElseIf (CancelSave <> True) Then 'Only throw an exception if the user *didn't* cancel the SavefileDialog
            Throw New Exception("File stream was nothing", New IOException())
        End If

    Catch ex As Exception
        MessageBox.Show(ex.Message & Environment.NewLine & FullyQualfiedPathName)
    End Try
    Return True
End Function

我看到的一个问题是您应该将 File.Open 放在 Using 块中:

Using fs = File.Open(fullyQualfiedPathName, FileMode.OpenOrCreate, FileAccess.ReadWrite)
    Using writer As New StreamWriter(fs) 'Create the stream writer
        writer.Write(writeData) 'Write the data
        'fs.Close() <--- you do not need this line becuase the "Using" block will take care of this for you.
    End Using
End Using

我不确定这是否会解决您的问题,因为我无法 运行 您的代码,但是 Using 块将自动关闭和清理一次性实例,例如 FileStreamStreamWriter,即使抛出异常。

顺便说一下,您应该为局部变量使用正确的命名约定(小驼峰式)。