System.IO.Streamwriter 在 VB.net 创建文件的地方出现零星问题,但出现错误,我无法将行写入文件



我最近偶尔在 StreamWriter 写入文件时遇到了一些问题,希望有人可以尝试阐明它。我对子例程的调用如下:

<!--Code Start
SubPrint(tagVal)
--> End of Code

而 sub 就是这个,目前我只是用一些随机数填充数组。(稍后我将遍历真实数据并以这种方式填充它):

<!--Code Start
Public Sub SubPrint(item As String)
    Dim sw As StreamWriter =
        New StreamWriter("C:UsersdlawrenceDesktopFred.txt", False)
    Dim tags() As Integer = {1, 3, 6, 2, 6, 2}
    Dim max As Integer = tags(0)
    For i = 1 To tags.Count - 1
        If tags(i) > max Then
            max = tags(i)
        End If
             sw.WriteLine(tags(i).ToString) 'EDIT moved this out of the If
    Next

End Sub
--> End of Code

它在运行时在我的桌面上创建文件"Fred.txt",但抛出异常错误:

<!--Error Log Start
System.IO.IOException
  HResult=0x80070020
  Message=The process cannot access the file 'C:UsersdlawrenceDesktopFred.txt' because it is being used by another process.
  Source=mscorlib
  StackTrace:
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamWriter.CreateFile(String path, Boolean append, Boolean checkHost)
   at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize, Boolean checkHost)
   at System.IO.StreamWriter..ctor(String path, Boolean append)
   at Tagging_App_GUI.Form1.SubPrint(String item) in C:UsersdlawrenceDocumentsiLogicIdeasForPunchedWindowsTagAddInNew AddInNewGUITagging App GUITagging App GUIForm1.vb:line 184
   at Tagging_App_GUI.Form1.BtnTag_Click(Object sender, EventArgs e) in C:UsersdlawrenceDocumentsiLogicIdeasForPunchedWindowsTagAddInNew AddInNewGUITagging App GUITagging App GUIForm1.vb:line 150
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun() in f:ddvbruntimemsvbalibApplicationServicesWindowsFormsApplicationBase.vb:line 779
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel() in f:ddvbruntimemsvbalibApplicationServicesWindowsFormsApplicationBase.vb:line 1471
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine) in f:ddvbruntimemsvbalibApplicationServicesWindowsFormsApplicationBase.vb:line 452
   at Tagging_App_GUI.My.MyApplication.Main(String[] Args) in :line 81
--> End of Error logging

前几天我很幸运地在不同的代码部分写了它,但不是今天。我正在使用 Imports 语句通过导入获取系统和 IO 命名空间 System.IO 重新启动系统不会带来任何乐趣。内部有一个异常,其值为"无"...

任何人都可以看到我没有看到的东西吗?谢谢!

问题是您没有closing StreamWriter,因此每次您尝试再次写入它时,它都在使用中,因此Error .

Next行后添加sw.Close,如下所示:

    Dim sw As IO.StreamWriter = New IO.StreamWriter("C:UsersdlawrenceDesktopFred.txt")
    Dim tags() As Integer = {1, 3, 6, 2, 6, 2}
    Dim max As Integer = tags(0)
    For i = 1 To tags.Count - 1
        If tags(i) > max Then
            max = tags(i)
        End If
        sw.WriteLine(tags(i).ToString) 'EDIT moved this out of the If
    Next
    sw.Close()

或者更好的是,在使用这样的StreamWriter时使用Using块:

    Using sw As IO.StreamWriter = New IO.StreamWriter("C:UsersdlawrenceDesktopFred.txt")
        Dim tags() As Integer = {1, 3, 6, 2, 6, 2}
        Dim max As Integer = tags(0)
        For i = 1 To tags.Count - 1
            If tags(i) > max Then
                max = tags(i)
            End If
            sw.WriteLine(tags(i).ToString) 'EDIT moved this out of the If
        Next
    End Using

最新更新