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

Sporadic problem with System.IO.Streamwriter in VB.net where it creates the file but comes up with an error that I can't write lines to the file

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

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

在我只是用一些随机数填充数组的那一刻,sub 就是这样。 (稍后我将遍历真实数据并以这种方式填充它):

<!--Code Start
Public Sub SubPrint(item As String)
    Dim sw As StreamWriter =
        New StreamWriter("C:\Users\dlawrence\Desktop\Fred.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:\Users\dlawrence\Desktop\Fred.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:\Users\dlawrence\Documents\iLogicIdeasForPunchedWindows\TagAddIn\New AddIn\NewGUI\Tagging App GUI\Tagging App GUI\Form1.vb:line 184
   at Tagging_App_GUI.Form1.BtnTag_Click(Object sender, EventArgs e) in C:\Users\dlawrence\Documents\iLogicIdeasForPunchedWindows\TagAddIn\New AddIn\NewGUI\Tagging App GUI\Tagging App GUI\Form1.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:\dd\vb\runtime\msvbalib\ApplicationServices\WindowsFormsApplicationBase.vb:line 779
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel() in f:\dd\vb\runtime\msvbalib\ApplicationServices\WindowsFormsApplicationBase.vb:line 1471
   at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine) in f:\dd\vb\runtime\msvbalib\ApplicationServices\WindowsFormsApplicationBase.vb:line 452
   at Tagging_App_GUI.My.MyApplication.Main(String[] Args) in :line 81
--> End of Error logging

前几天我曾在不同的代码部分写过它,但今天不是。我正在使用 Imports 语句通过 Imports System.IO 获取系统和 IO 名称空间。重新启动系统没有带来任何乐趣。有一个内部异常,其值为 Nothing...

有人能看到我没看到的东西吗?谢谢!

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

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

    Dim sw As IO.StreamWriter = New IO.StreamWriter("C:\Users\dlawrence\Desktop\Fred.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:\Users\dlawrence\Desktop\Fred.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