We have talked about three approaches to erase a shared parameter with VB.NET before. Two failed with exceptions and one seemingly succeeded but the result was not really what we wanted.
In this post, let’s see how to work around the problem.
Through checking on the shared parameter external definition file, it is obvious that we can remove the entry from the text file directly. To achieve this goal, we need to parse the file format a bit, seek the shared parameter entry of interest, and modify the file programmatically with VB.NET.
Here we go:
…
RemoveSharedParameterFromFile(@"Volume41", @"c:\temp\sharedparameters.txt")
…
Public Shared Function RemoveSharedParameterFromFile(ByVal paramName As String, ByVal fileName As String) As Boolean
Dim lines As List(Of String()) = ReadSharedParameterFile(fileName)
Dim index As Integer = -1
If lines.Count > 6 Then
For i As Integer = 6 To lines.Count - 1
If lines(i)(2) = paramName Then
index = i
Exit For
End If
Next
End If
If index <> -1 Then
lines.RemoveAt(index)
WriteContentBackToTxtFile(lines, fileName)
Return True
End If
Return False
End Function
Public Shared Sub WriteContentBackToTxtFile(ByVal lines As List(Of String()), ByVal path As String)
Using writer As New StreamWriter(path)
For Each line As String() In lines
Dim lineContent As String = String.Empty
For Each str As String In line
lineContent += String.Format("{0}" & vbTab, str)
Next
lineContent.Remove(lineContent.Length - 1)
writer.WriteLine(lineContent)
Next
End Using
End Sub
Public Shared Function ReadSharedParameterFile(ByVal path As String) As List(Of String())
Dim lines As New List(Of String())()
Using reader As New StreamReader(path)
While Not reader.EndOfStream
Dim line As String() = reader.ReadLine().Split(ControlChars.Tab)
If line IsNot Nothing AndAlso line.Length > 0 Then
lines.Add(line)
End If
End While
End Using
Return lines
End Function
The code works perfectly to remove the first found shared parameter definition with the given name from the external definition file. After it is run, we can verify from the Share Parameters user interface that the shared parameter will be gone.
However, due to the nature of shared parameters, i.e. duplicate names can exist, it may be necessary to improve the methods to compare parameter type and some other criteria to make sure the shared parameter of real concern is got rid of.
Anyway, it proves to be a feasible way and can be made reliably enough.
SharedParameter Eraser of RevitAddinWizard will exercise the approach in both C# and VB.NET.
Recent Comments