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

时间:2015-12-01 13:26:36

标签: vb.net file-io streamwriter

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

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

我目前已经对下面的函数进行了编码,但我一直有例外:

  

无法访问已关闭的文件

文件创建得很好,但是为空(它应该包含"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

1 个答案:

答案 0 :(得分:2)

我看到的一个问题是您应该将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块会自动处理关闭和清理一次性实例,例如{{1即使抛出异常,也会出现FileStream

顺便说一下,你应该为局部变量使用适当的命名约定(较低的驼峰情况)。