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

1

I've been having some problems with StreamWriter writing to a file sporadically lately and hopefully someone can try to shed some light on it. My call to the subroutine is the following:

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

And the sub is simply this at the moment where I am just populating the array with some random numbers. (I'll later be iterating through real data and populating it that way):

<!--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

It creates the file "Fred.txt" on my desktop at runtime, but throws the exception error:

<!--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

I've had luck writing to it the other day in a different section of code, but not today. I am using the Imports statement to get both the system and IO name spaces via Imports System.IO A restart of the system produced no joy. There was an inside Exception whose value was Nothing...

Can anyone see something I'm not seeing? Thank you!

vb.net
streamwriter
asked on Stack Overflow Feb 1, 2019 by TheDudeAbides • edited Feb 1, 2019 by TheDudeAbides

1 Answer

1

The problem is you are not closing the StreamWriter thus every time you try to write to it again it's in use, hence the Error.

Add sw.Close after the Next line like so:

    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()

or better still, use a Using block when using StreamWriter like so:

    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
answered on Stack Overflow Feb 2, 2019 by video.baba

User contributions licensed under CC BY-SA 3.0