Saving array to file

Cheeky

Member
Joined
Aug 25, 2005
Messages
5
Location
Slovenia, EU
Programming Experience
Beginner
[RESOLVED] Saving array to file

In my VB.NET application I have defined two dimensional array.

VB.NET:
Public position(1000, 1) As Decimal

I'd like to save that array to an ordinary text file - first array dimension would be first column, then two tabs and then second array dimension. Something like this:

VB.NET:
dim1_0 		  dim2_0
dim1_1		  dim2_1
dim1_2		  dim2_2
dim1_3		  dim2_3
...	          ...
...	          ...
dim1_999	  dim2_999
 
Last edited:
VB.NET:
	'For 1000 x 2 elements use (999, 1)
	Public position(999, 1) As Decimal

	Private Sub SaveArray()
		Dim myWriter As New IO.StreamWriter("file name here.")

		For row As Integer = 0 To Me.position.GetUpperBound(0) Step 1
			myWriter.WriteLine(String.Format("{0}{1}{1}{2}", _
											 Me.position(row, 0), _
											 Convert.ToChar(Keys.Tab), _
											 Me.position(row, 1)))
		Next

		myWriter.Close()
	End Sub
 
typo

Thank you for your repy. It works just as I wanted, but it needs a little tweaking:

- my array is decimal and I would only want to limit the output to 5 digits after the decimal for each element of array.
In some other place I used this code to limit output digits:
VB.NET:
While a < 14
	array_value_x(a) = value_x(a).ToString("0.00")
	a = a + 1
End While
But here I just don't know where to include it in the code you wrote above.

- The array is filled by some math function that has some start conditions and depending on those conditions, array fills up. Worst case is that the array is full (no zero elements), but with other than WC start conditions, there are zero elements at the end. Currently I'm using fixed array and I can calculate the size of array pretty accurate (+5 elements max.), which is ok with me. Can I resize an array after I calculate the lenght? (so the function that writes to file can stay prett much the same).

- Is there an easy way to let the user of that program select folder and filename, where he would like to save that txt? Like "Save As" window in most applications. Now it just writes itself in /bin folder of my project.
 
Note that if you use ToString("0.00000") or ToString("n5") to format your output then you will ALWAYS get 5 decimal places whether the number includes them or not. For example, (1.11111).ToString("0.000") produces "1.111" and (1.1).ToString("0.000") produces "1.100". If that's what you want then that's cool. If not, you should limit the number of decimal places to 5 using Decimal.Round(myDecimal, 5), which will then only show decimal places if they are present and will show no more than 5 decimal places. Here's my code altered to use a bit of both, so you would know where to put either:
VB.NET:
		For row As Integer = 0 To Me.position.GetUpperBound(0) Step 1
			myWriter.WriteLine(String.Format("{0}{1}{1}{2}", _
											 Me.position(row, 0).ToString("n5"), _
											 Convert.ToChar(Keys.Tab), _
											 Decimal.Round(Me.position(row, 1), 5)))
		Next
After you have filled the array, you can use ReDim to resize it. Assuming you wanted to reduce the size from 1000 to 736 rows, you would use code like this:
VB.NET:
ReDim Preserve Me.position(735, 1)
Do not forget the Preserve keyword or all the current data will be lost.

To allow the user to select a location to save you would use a SaveFileDialog like this:
VB.NET:
Dim sfd As New SaveFileDialog

If sfd.ShowDialog() = DialogResult.OK Then
	'Save to the selected file here using the sfd.FileName property.
End If
You can play around with various properties of the SaveFileDialog to modify its behaviour.
 
This is how I did it. I have a feeling that I'm still doing something wrong with saving files.
I have a picture in picturebox2, that I want to save and the text from array - so there are two save as dialog boxes (so far everything is ok).

The problem is that "Save as type" dropdown menu is empty (in one savebox should be .png, in other .txt) and so far I can only save these two files without extensions (picture), unless I type them as a file name (picture.png). My improvised solution to this would be to add .png and .txt at the end of filename string.

Is there a possibility to use only one save as dialog box? So that the user only enters file name once (data) and both (data.png and data.txt) would save? (In that case "Save as type" dropdown menu would have to stay empty)

You can play around with various properties of the SaveFileDialog to modify its behaviour.

Ok - call me stupid, but did you mean the properties window or just setting properties with code. With the second I'm not too familiar.

VB.NET:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

		Dim save_pic As New SaveFileDialog
		Dim save_txt As New SaveFileDialog
		Dim pic_name As String
		Dim txt_name As String

		'Save dialog for picturebox2
		If save_pic.ShowDialog() = DialogResult.OK Then
			pic_name = save_pic.FileName.ToString
			PictureBox2.Image.Save(pic_name, ImageFormat.Png)

		End If
	    
		'Save dialog for text file
		If save_txt.ShowDialog() = DialogResult.OK Then
			txt_name = save_txt.FileName.ToString
			Dim myWriter As New IO.StreamWriter(txt_name)

			For row As Integer = 0 To Me.position.GetUpperBound(0) Step 1
			    myWriter.WriteLine(String.Format("{0}{1}{1}{2}", _
					 ' First column is saved in format 0.00 - if digits are mising, zeroes are addded
					 Me.position(row, 0).ToString("0.00"), _
					 Convert.ToChar(Keys.Tab), _
					 ' First column is saved in format 0.00000 - if digits are mising, zeroes are addded
					 Me.position(row, 1).ToString("0.00000")))
			Next
			myWriter.Close()
		End If

	End Sub

I'm really grateful for your help.
 
You can set the properties of the SaveFileDialog in the designer, but only if you add it to the form in the designer. Any property you can set in the designer can be set in code though. I suggest you read some of the help topics related to the SaveFileDialog. Just do a help search for "SaveFileDialog members" and you will get a match that lists all the member properties, methods, etc. You should be particularly interested in DefaultExt, AddExtension and Filter. You can do this for any class, and I recommend that you do do it for any classes you use. It's the best way to get an understanding of the objects you're using.

If you want to use a single dialogue for both the image and the text file, I assume that you are intending to use the same location and file name for each, but with a different extension. I'd just have the user select a location to save the image and then do this:
VB.NET:
Dim imagePath As String = sfd.FileName
Dim textPath As String = IO.Path.ChangeExtension(imagePath, ".txt")
 
Thank you for the advice. I did a search and I have only one more question - I want to add OverwritePrompt like I found in an example here.
But the problem - I later add the extensions to both files and file.txt that is saved is not equal to file (without extension).
So if I save with name file, it doesn't prompt to overwrite previous file, but if I save with file.txt it prompts.

VB.NET:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

		Dim sfd As New SaveFileDialog

		If sfd.ShowDialog() = DialogResult.OK Then
			Dim path As String = sfd.FileName
			sfd.OverwritePrompt = True
			sfd.DefaultExt = "txt"
			sfd.Filter = "Text files (*.txt)|*.txt"
			Dim textPath As String = IO.Path.ChangeExtension(path, ".txt")
			Dim imgPath As String = IO.Path.ChangeExtension(path, ".png")
			PictureBox2.Image.Save(imgPath, ImageFormat.Png)

			Dim myWriter As New IO.StreamWriter(textPath)
			For row As Integer = 0 To Me.position.GetUpperBound(0) Step 1
			    myWriter.WriteLine(String.Format("{0}{1}{1}{2}", _
						 Me.position(row, 0).ToString("0.00"), _
						 Convert.ToChar(Keys.Tab), _
						 Me.position(row, 1).ToString("0.00000")))
			Next
		End If 

	End Sub

As you can see I also added:
VB.NET:
sfd.DefaultExt = "txt"
sfd.Filter = "Text files (*.txt)|*.txt"

so that .txt would be automaticaly added to file name, but I'm probably still missing something, because it doesn't work as it should.
 
You have to set the properties of the SFD before calling ShowDialog. You're setting them after the user has already closed it so it's too late for them to have any effect.
 
Back
Top