Write to text file, and read from that text file

Write to text file, and read from that text file

blandb
Mentor Mentor
813 Views
3 Replies
Message 1 of 4

Write to text file, and read from that text file

blandb
Mentor
Mentor

I have external rules that assist in populating a lot of components and constrains them together. Every time I run the rule, there are certain things I really only need to set once. For example, I don't need to choose the wall thickness, finish, seal types every time. Those are pick lists that I'd like to send the selected values to an external text file and reference the stored values when I run the rule again. Those items are the same for the whole job so no need to repetitively choose the same thing over and over for every time the rule is ran. I only want to select them once and just refer to the stored values. I am not placing these into user parameters as our assembly templates can be used for multiple things, and I don't want finish and seal type as user parameters where they are kind of irrelevant for that particular assembly.

 

So the thought would be, write common items to a .txt file, then when the rule is ran, it will look for this text file, grab the needed parameters and use them.

 

I know there is a snippets for writing and reading, but when reading it appears to put it all as 1 string? What would be the best way to 

 

Dim First_Name As String = "first"
Dim Last_Name As String = "last"

'____Create and write to a text file_________________
oWrite = System.IO.File.CreateText(ThisDoc.PathAndFileName(False) & ".txt")
oWrite.WriteLine(First_Name)
oWrite.WriteLine(Last_Name)
oWrite.Close()
'open the file
ThisDoc.Launch(ThisDoc.PathAndFileName(False) & ".txt")
 '____Open and read a text file_______________________
oRead = System.IO.File.OpenText(ThisDoc.PathAndFileName(False) & ".txt")
EntireFile = oRead.ReadToEnd()
oRead.Close()
MsgBox(EntireFile, MsgBoxStyle.Information, "Text File Contents")

 

blandb_0-1700259413392.png

 

Autodesk Certified Professional
0 Likes
Accepted solutions (2)
814 Views
3 Replies
Replies (3)
Message 2 of 4

Michael.Navara
Advisor
Advisor
Accepted solution

You can easily write and read text file line by line using this sample

Sub WriteLinesToFile()
    Dim First_Name As String = "first"
    Dim Last_Name As String = "last"

    IO.File.WriteAllLines("C:\Temp\settings.txt", {First_Name, Last_Name})
End Sub


Sub ReadLinesFromFile()
    Dim readAllLines As String() = IO.File.ReadAllLines("C:\Temp\settings.txt")
    For Each line As String In readAllLines
        MessageBox.Show(line)
    Next
End Sub

 

Or for more complex parameters you can define your own class and implement serialization of this class. It is useful when you want to work with more complex values then strings. This class can be placed in separate .vb file and referenced using AddVbFile. The biggest advantage of this approach is in appropriate value types of variables. This is recognized by IntelliSense.

 

Sample usage:

AddReference "System.Xml.dll"
AddReference "System.IO.dll"
AddVbFile "C:\Path\To\MyParameters.vb"


Sub Main
	Dim settingFile As String = "C:\Temp\settings.xml"

	'Create new instance of parameters class
	Dim parameters As New MyParameters
	'Set values
	parameters.Text = "Some text"
	parameters.Number = 1
	parameters.TrueFalse = True
	'Save to file
	parameters.SaveToFile(settingFile)


	'Load from file to new variable
	Dim parameters2 = MyParameters.LoadFromFile(settingFile)
	If parameters2 Is Nothing Then
		Logger.Error("Parameters wasn't initialized before. Initialize them now")
		parameters2 = New MyParameters()
	End If
	'Use values
	Logger.Debug(parameters2.Text)
	Logger.Debug(parameters2.Number)
	Logger.Debug(parameters2.TrueFalse)

End Sub

 

MyParameters.vb content

Imports System.XML
Imports System.IO

''' <summary>
''' This class can be shared in separate file and referenced using AddVbFile "C:\Path\To\MyParameters.vb"
''' <para>Requires refe</para>
''' </summary>
Public Class MyParameters

	'Parameters declaration with default values
	Public Text As String = "Default text" :
	Public Number As Double = 0
	Public TrueFalse As Boolean = False


	Public Sub SaveToFile(Optional fileName As String = "C:\Temp\settings.xml")
		Dim xs = New System.Xml.Serialization.XmlSerializer(GetType(MyParameters))
		Dim stream As System.IO.TextWriter = New System.IO.StringWriter()
		xs.Serialize(stream, Me)
		Dim xmlString = stream.ToString()
		System.IO.File.WriteAllText(fileName, xmlString)
	End Sub


	Public Shared Function LoadFromFile(Optional fileName As String = "C:\Temp\settings.xml") As MyParameters
		Try
			Dim xmlString As String = System.IO.File.ReadAllText(fileName)
			Dim xs = New System.Xml.Serialization.XmlSerializer(GetType(MyParameters))

			Dim reader As System.IO.TextReader = New System.IO.StringReader(xmlString)
			Dim xReader As System.Xml.XmlReader = New System.XML.XmlTextReader(reader)

			Dim deserializedMyParameters As MyParameters = xs.Deserialize(xReader)
			Return deserializedMyParameters

		Catch
			Return Nothing
		End Try
	End Function
End Class
0 Likes
Message 3 of 4

blandb
Mentor
Mentor

In the first example you have, what would be the best approach to run a different rule, and look at the text file, read specific variables to be able to populate the first and last name in the rule that was launched? I'm not making that connection. Sorry. I guess I'm looking at the text file as a place to store pre-defined variables, and then when needed, refer to this text file and use the stored values to populate other variables when a rule is ran.

Autodesk Certified Professional
0 Likes
Message 4 of 4

Frederick_Law
Mentor
Mentor
Accepted solution

Write variable name and value, like a CSV file.

First Name; Bob

Last Name; Son

Age; 20

 

If you always read them in same order, you can just list them.

Bob; Son; 20

 

xml will be easier if you need to read one "randomly".

 

Readln will start from beginning or continue from last Readline until EoF.

0 Likes