[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

how to close and re-open a stream reader object

Posted on 2016-10-04
5
Medium Priority
?
43 Views
Last Modified: 2016-10-06
I am running into some issues where I throw an error when my file location is not available and in my catch statement I want to select a new file location that does exist.

Here is the code:

  Try
                    'Starts the process to Write the file in the defined export location.
                    Dim Stream As FileStream = New FileStream(exportFile.FullName, FileMode.Append)
                    Dim streamWriter As New StreamWriter(Stream)
                    streamWriter.Write(strExportHeader & strExportText)
                    streamWriter.Close()
                    Stream.Close()
                    'This is triggered if export folder has change or has been deleted and canoot find the Partfile Export location.
                Catch dirEx As DirectoryNotFoundException
                    mainFormStatusStripLabel.Font = New Font(mainFormStatusStripLabel.Font.FontFamily, 8, FontStyle.Regular)
                    mainFormStatusStripLabel.BackColor = System.Drawing.Color.Red
                    mainFormStatusStripLabel.Text = "The following export directory was not found..."
                    Dim Stream As FileStream = New FileStream(masterSettings.masterExport.masterExportOfflineLocation, FileMode.Append)
                    Dim streamWriter As New StreamWriter(Stream)
                    streamWriter.Write(strExportHeader & strExportText)
                    streamWriter.Close()
                    Stream.Close()
                Catch wio As IOException
                    Dim errStr As String
                    errStr = "The following export could not be written to. The file could be in use or corrupt..." & vbCrLf & vbCrLf
                    errStr += exportFile.FullName & vbCrLf & vbCrLf
                    errStr += "Press OK to select as temporary directory. NOTE: This must be changed in the Configuration or this dialog will continue to appear."
                    MessageBox.Show(errStr, "File In Use", MessageBoxButtons.OK, MessageBoxIcon.Warning)
                    Return -10
                End Try
0
Comment
Question by:cmdolcet
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 34

Accepted Solution

by:
it_saige earned 2000 total points
ID: 41828380
The solution is to move your stream variable declarations outside the try...catch block and initialize them inside the try...catch block; e.g. -
Dim [stream] As FileStream = Nothing
Dim [writer] As StreamWriter = Nothing
Try
	'Starts the process to Write the file in the defined export location.
	[stream] = New FileStream(exportFile.FullName, FileMode.Append)
	[writer] = New StreamWriter([stream])
	[writer].Write(strExportHeader & strExportText)
	'This is triggered if export folder has change or has been deleted and canoot find the Partfile Export location.
Catch dirEx As DirectoryNotFoundException
	If [writer] IsNot Nothing Then [writer].Dispose()
	If [stream] IsNot Nothing Then [stream].Dispose()

	[writer] = Nothing
	[stream] = Nothing

	mainFormStatusStripLabel.Font = New Font(mainFormStatusStripLabel.Font.FontFamily, 8, FontStyle.Regular)
	mainFormStatusStripLabel.BackColor = System.Drawing.Color.Red
	mainFormStatusStripLabel.Text = "The following export directory was not found..."
	Try
		[stream] = New FileStream(masterSettings.masterExport.masterExportOfflineLocation, FileMode.Append)
		[writer] = New StreamWriter([stream])
		[writer].Write(strExportHeader & strExportText)
	Finally
		If [writer] IsNot Nothing Then [writer].Dispose()
		If [stream] IsNot Nothing Then [stream].Dispose()

		[writer] = Nothing
		[stream] = Nothing
	End Try
Catch wio As IOException
	Dim errStr As String
	errStr = "The following export could not be written to. The file could be in use or corrupt..." & vbCrLf & vbCrLf
	errStr += exportFile.FullName & vbCrLf & vbCrLf
	errStr += "Press OK to select as temporary directory. NOTE: This must be changed in the Configuration or this dialog will continue to appear."
	MessageBox.Show(errStr, "File In Use", MessageBoxButtons.OK, MessageBoxIcon.Warning)
	Return -10
Finally
	If [writer] IsNot Nothing Then [writer].Dispose()
	If [stream] IsNot Nothing Then [stream].Dispose()

	[writer] = Nothing
	[stream] = Nothing
End Try

Open in new window

OR

Use using statements, which basically encapsulates each variable declaration and initialization within it's own try...finally block; e.g. -
Try
	'Starts the process to Write the file in the defined export location.
	Using [stream] As New FileStream(exportFile.FullName, FileMode.Append)
		Using [writer] As New StreamWriter([stream])
			[writer].Write(strExportHeader & strExportText)
		End Using
	End Using
	'This is triggered if export folder has change or has been deleted and canoot find the Partfile Export location.
Catch dirEx As DirectoryNotFoundException
	mainFormStatusStripLabel.Font = New Font(mainFormStatusStripLabel.Font.FontFamily, 8, FontStyle.Regular)
	mainFormStatusStripLabel.BackColor = System.Drawing.Color.Red
	mainFormStatusStripLabel.Text = "The following export directory was not found..."
	Using [stream] As New FileStream(masterSettings.masterExport.masterExportOfflineLocation, FileMode.Append)
		Using [writer] As New StreamWriter([stream])
			[writer].Write(strExportHeader & strExportText)
		End Using
	End Using
Catch wio As IOException
	Dim errStr As String
	errStr = "The following export could not be written to. The file could be in use or corrupt..." & vbCrLf & vbCrLf
	errStr += exportFile.FullName & vbCrLf & vbCrLf
	errStr += "Press OK to select as temporary directory. NOTE: This must be changed in the Configuration or this dialog will continue to appear."
	MessageBox.Show(errStr, "File In Use", MessageBoxButtons.OK, MessageBoxIcon.Warning)
	Return -10
End Try

Open in new window


-saige-
0
 

Author Comment

by:cmdolcet
ID: 41830552
it_saige,

Taking your first example into my code. I get to the:

Try
            [stream] = New FileStream(masterSettings.masterExport.masterExportOfflineLocation, FileMode.Append)  

and ten it jumps to the Finally statement.

Any idea as to why?
0
 

Author Comment

by:cmdolcet
ID: 41830558
It says fileStream is a type and cannot be used as an expression?
0
 
LVL 34

Expert Comment

by:it_saige
ID: 41830631
Both methods work for me:

Test code:
Imports System.IO

Module Module1
	Sub Main()
		Console.WriteLine("Running example 1: {0}", Example1())
		Console.WriteLine("Running example 2: {0}", Example2())
		Console.ReadLine()
	End Sub

	Function Example1() As Integer
		Dim [stream] As FileStream = Nothing
		Dim [writer] As StreamWriter = Nothing
		Try
			'Starts the process to Write the file in the defined export location.
			[stream] = New FileStream("C:\_admin\EE_Q28974184\testing1\testingex1.txt", FileMode.Append)
			[writer] = New StreamWriter([stream])
			[writer].Write("This is a test of example1")
			'This is triggered if export folder has change or has been deleted and canoot find the Partfile Export location.
		Catch dirEx As DirectoryNotFoundException
			If [writer] IsNot Nothing Then [writer].Dispose()
			If [stream] IsNot Nothing Then [stream].Dispose()

			[writer] = Nothing
			[stream] = Nothing

			Try
				[stream] = New FileStream("C:\_admin\EE_Q28974184\testingex1.txt", FileMode.Append)
				[writer] = New StreamWriter([stream])
				[writer].Write("This is a test of example1")
			Finally
				If [writer] IsNot Nothing Then [writer].Dispose()
				If [stream] IsNot Nothing Then [stream].Dispose()

				[writer] = Nothing
				[stream] = Nothing
			End Try
		Catch wio As IOException
			Console.WriteLine(wio.Message)
			Return -10
		Finally
			If [writer] IsNot Nothing Then [writer].Dispose()
			If [stream] IsNot Nothing Then [stream].Dispose()

			[writer] = Nothing
			[stream] = Nothing
		End Try
	End Function

	Function Example2() As Integer
		Try
			'Starts the process to Write the file in the defined export location.
			Using [stream] As New FileStream("C:\_admin\EE_Q28974184\testing2\testingex2.txt", FileMode.Append)
				Using [writer] As New StreamWriter([stream])
					[writer].Write("This is a test of example2")
				End Using
			End Using
			'This is triggered if export folder has change or has been deleted and canoot find the Partfile Export location.
		Catch dirEx As DirectoryNotFoundException
			Using [stream] As New FileStream("C:\_admin\EE_Q28974184\testingex2.txt", FileMode.Append)
				Using [writer] As New StreamWriter([stream])
					[writer].Write("This is a test of example2")
				End Using
			End Using
		Catch wio As IOException
			Console.WriteLine(wio.Message)
			Return -10
		End Try
	End Function
End Module

Open in new window

Test folders:Capture.JPGTest output:Capture.JPGSuccessful output:Capture.JPGExceptional output:Capture.JPG
-saige-
0
 
LVL 34

Expert Comment

by:it_saige
ID: 41830640
It is possible, though, that you have a class or module that is named fileStream.  If this is the case try explicitly declaring the usage of filestream; e.g. -
Module Module1
	Sub Main()
		Console.WriteLine("Running example 1: {0}", Example1())
		Console.WriteLine("Running example 2: {0}", Example2())
		Console.ReadLine()
	End Sub

	Function Example1() As Integer
		Dim [stream] As System.IO.FileStream = Nothing
		Dim [writer] As System.IO.StreamWriter = Nothing
		Try
			'Starts the process to Write the file in the defined export location.
			[stream] = New System.IO.FileStream("C:\_admin\EE_Q28974184\testing1\testingex1.txt", System.IO.FileMode.Append)
			[writer] = New System.IO.StreamWriter([stream])
			[writer].Write("This is a test of example1")
			'This is triggered if export folder has change or has been deleted and canoot find the Partfile Export location.
		Catch ex As System.IO.DirectoryNotFoundException
			If [writer] IsNot Nothing Then [writer].Dispose()
			If [stream] IsNot Nothing Then [stream].Dispose()

			[writer] = Nothing
			[stream] = Nothing

			Try
				[stream] = New System.IO.FileStream("C:\_admin\EE_Q28974184\testingex1.txt", System.IO.FileMode.Append)
				[writer] = New System.IO.StreamWriter([stream])
				[writer].Write("This is a test of example1")
			Finally
				If [writer] IsNot Nothing Then [writer].Dispose()
				If [stream] IsNot Nothing Then [stream].Dispose()

				[writer] = Nothing
				[stream] = Nothing
			End Try
		Catch ex As System.IO.IOException
			Console.WriteLine(ex.Message)
			Return -10
		Finally
			If [writer] IsNot Nothing Then [writer].Dispose()
			If [stream] IsNot Nothing Then [stream].Dispose()

			[writer] = Nothing
			[stream] = Nothing
		End Try
	End Function

	Function Example2() As Integer
		Try
			'Starts the process to Write the file in the defined export location.
			Using [stream] As New System.IO.FileStream("C:\_admin\EE_Q28974184\testing2\testingex2.txt", System.IO.FileMode.Append)
				Using [writer] As New System.IO.StreamWriter([stream])
					[writer].Write("This is a test of example2")
				End Using
			End Using
			'This is triggered if export folder has change or has been deleted and canoot find the Partfile Export location.
		Catch ex As System.IO.DirectoryNotFoundException
			Using [stream] As New System.IO.FileStream("C:\_admin\EE_Q28974184\testingex2.txt", System.IO.FileMode.Append)
				Using [writer] As New System.IO.StreamWriter([stream])
					[writer].Write("This is a test of example2")
				End Using
			End Using
		Catch ex As System.IO.IOException
			Console.WriteLine(ex.Message)
			Return -10
		End Try
	End Function
End Module

Open in new window

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses

656 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question