VB.net中System.IO.Streamwriter偶尔出现问题,它创建了文件,但出现了一个错误,我可以';不要在文件中写入行

VB.net中System.IO.Streamwriter偶尔出现问题,它创建了文件,但出现了一个错误,我可以';不要在文件中写入行,vb.net,streamwriter,Vb.net,Streamwriter,最近,我在StreamWriter偶尔向文件写入时遇到了一些问题,希望有人能对此有所了解。我对子程序的调用如下: <!--Code Start SubPrint(tagVal) --> End of Code 代码结束 sub就是现在我用一些随机数填充数组的地方。(我稍后将迭代实际数据并以这种方式填充): 代码结束 它在运行时在我的桌面上创建文件“Fred.txt”,但抛出异常错误: <!--Error Log Start System.IO.IOException

最近,我在StreamWriter偶尔向文件写入时遇到了一些问题,希望有人能对此有所了解。我对子程序的调用如下:

<!--Code Start
SubPrint(tagVal)
--> End of Code
代码结束
sub就是现在我用一些随机数填充数组的地方。(我稍后将迭代实际数据并以这种方式填充):

代码结束
它在运行时在我的桌面上创建文件“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


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

问题在于您没有关闭
StreamWriter
,因此每次尝试再次写入时,它都在使用中,因此出现
错误

下一行之后添加
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

每次调用该方法时,它是否总是一个新文件,或者当文件已经存在并且您打算覆盖或附加到它时,您是否会调用它?哦,我也尝试了附加参数。事实上,我简化了一个b/c设置为False,这样构造函数每次都会创建(或覆盖)。事实上,我只是尝试了一个简单的控制台应用程序和一个快速而肮脏的新功能,但仍然没有乐趣:你仍然没有回答我的问题。你在干什么?始终创建一个新文件,或附加到已经存在的文件中?导入System.IO Module Module1 Dim TagVal作为String=“HH1”Sub-Main()子打印(TagVal)End Sub-Public子打印(项目作为字符串)Dim sw作为StreamWriter=新StreamWriter(“C:\Users\dlawrence\Desktop\Fred.txt”,False)Dim标记()As Integer={1,3,6,2,6,2}Dim max As Integer=tags(0)表示i=1到tags。如果tags(i)>max,则计数-1;如果sw.Write(tags(i).ToString,则max=tags(i)结束“编辑将其从If Next End Sub End模块中移出。我将创建一个不存在的模块。哦,该死。我在原始代码中也注释了close()。非常感谢!…现在,在看到内存堆栈后,我也可以将其设置为nothing。
    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