Community
Inventor Programming - iLogic, Macros, AddIns & Apprentice
Inventor iLogic, Macros, AddIns & Apprentice Forum. Share your knowledge, ask questions, and explore popular Inventor topics related to programming, creating add-ins, macros, working with the API or creating iLogic tools.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Batch rename part files

12 REPLIES 12
SOLVED
Reply
Message 1 of 13
karram
836 Views, 12 Replies

Batch rename part files

Hello All,

 

I have an assembly in vault with more than 100 parts, and each part is named starting with '0980_xxxx.ipt.' Now, I need to rename all the '0980_xxxx.ipt' files to '0970_xxxx.ipt' for each part file. How can I simplify this renaming process, ideally with a single-click solution or using simple stems?

 

Thanks

Br

Karthick

12 REPLIES 12
Message 2 of 13
A.Acheson
in reply to: karram

Hi @karram 

It will likely be the easiest to check out all you files to a single assembly. Then run through the documents and perform a save as and use a replace function to replace 70 for 80. This assumes there isn't another 80 in your file name. 

 

Do you think you can start making up the code to carry this out? Keep in mind this is a help forum and not a do forum so I will give some pointers and you can see what works.

 

Firstly see this post for working with assemblies and the most direct is to work with documents.

 

 

Sub Main
   ShowReferences()
End Sub

Public Sub ShowReferences()
    ' Get the active assembly.
    Dim oAsmDoc As AssemblyDocument = ThisApplication.ActiveDocument
    ' Get all of the referenced documents.
    Dim oRefDocs As DocumentsEnumerator = oAsmDoc.AllReferencedDocuments

    ' Iterate through the list of documents.
    Dim oRefDoc As Document
    For Each oRefDoc In oRefDocs
        Logger.Info(oRefDoc.FullFileName)
    Next
End Sub

 

Once you can access each document you can

then work to change the filename using replace string function see help page here.

Check you replace with a message box before doing any operation with the filename.

 

Dim TestString As String = "Shopping List"  
' Returns "Shipping List".  
Dim aString As String = Replace(TestString, "o", "i")  

 

 

And finally you can do a save as on the document help page here

Syntax

Document.SaveAsFileName As String, SaveCopyAs As Boolean )

 

If this solved a problem, please click (accept) as solution.‌‌‌‌
Or if this helped you, please, click (like)‌‌
Regards
Alan
Message 3 of 13
karram
in reply to: A.Acheson

I don't think so. I am not able to compile your code in the correct format. Also, I don't know where the 'show reference' function could be started. Should I use this iLogic code in an Assembly environment? Can you help me a little bit more to start the code structure?

Thanks

Message 4 of 13
WCrihfield
in reply to: karram

Hi @karram.  I do not currently use Vault, and have not used it before either, so I am not sure how having Vault involved in this process of renaming Inventor files will work on your end.  I do know that traditionally, when you rename Inventor files, that usually cased a mess.  Because then you have to figure out what all other assemblies, drawings, and such were referencing that file, then open each of those other Inventor documents, then fix the now broken reference, and redirect all of those to the renamed file.  If Vault is involved, then I assume that this may be easier to deal with, but I am not sure.  But I would definitely not be able to write a simple iLogic rule to reach into your Vault file space, and rename files in there, because they would be protected by that Vault system (they would all be like ReadOnly).

 

However, if those files were all copied locally on your computer, then at least those files may not be seen as ReadOnly.  Still, in order for Vault to know that you renamed all those files, and know what to do with those renamed files, that is another story altogether, and I do not know how that would work on your end.

 

That being said, I do have a highly experimental (and untested) iLogic rule that you could review for ideas towards designing your own solution for this type of task.  If you plan on testing this code as it currently is, I highly recommend that you only try this out on files that are completely unrelated to anything production related, and only on files that are not important in any way to start with, because they may get all messed up.

 

  • This code will first launch a file browser dialog, and ask you to select an assembly file to start from.
  • If a valid selection is made, it will then open that assembly invisibly (not visible, no document tab).
  • Then it will try to get the collection of files that it references.
  • Then it will start a process (block of code) that will attempt to iterate through each of those file references, and if any of those file references references any other files, this process will also attempt to iterate through those too (recursively).
  • For each file reference:
    • Gets its full file name (path, file name, & file extension)
    • Check if its file name starts with the 'old prefix' ("0980_").
    • If it does, it will create a new full file name (just a String) with that old prefix replaced by the 'new prefix' ("0970_").
    • Then checks if any already existing file already has that 'new' full file name.
      • If an existing file does exist, it writes that to the iLogic Log window, with a Warning, and does not rename the old file.
    • If no existing file with the new name was found, it renames the existing file with the new name.
    • If it renamed the file, then it will also try to replace that file reference using the newly renamed file.
    • If it fails to rename the file, or fails to replace that file reference, it will also write an error message to the iLogic Log window about this incident.

...At least that was the plan...

Sub Main
	Dim sSourceFile As String = UseFileDialog(True, "Select Source Assembly File.")
	If sSourceFile = "" Then Return
'	ThisApplication.FileManager.IsFileNameValid(sSourceFile)
	Dim oSourceDoc As Inventor.Document = ThisApplication.Documents.Open(sSourceFile, False)
	Dim oRefFileDescs As Inventor.FileDescriptorsEnumerator = oSourceDoc.File.ReferencedFileDescriptors
	RecurseFileDescriptors(oRefFileDescs, AddressOf ProcessFileDescriptor)
	oSourceDoc.Update2(True)
	oSourceDoc.Save2(True)
End Sub

Function UseFileDialog(Optional bSave As Boolean = False, Optional sTitle As String = vbNullString, _
Optional sInitialDirectory As String = vbNullString, Optional sFileName As String = vbNullString) As String
	Dim oFDlg As Inventor.FileDialog : ThisApplication.CreateFileDialog(oFDlg)
	If Not String.IsNullOrEmpty(sTitle) Then oFDlg.DialogTitle = sTitle
	If String.IsNullOrEmpty(sInitialDirectory) Then
		oFDlg.InitialDirectory = ThisApplication.DesignProjectManager.ActiveDesignProject.WorkspacePath
	Else
		oFDlg.InitialDirectory = sInitialDirectory
	End If
	If Not String.IsNullOrEmpty(sFileName) Then oFDlg.FileName = sFileName
	oFDlg.Filter = "Autodesk Inventor Files (*.iam;*.dwg;*.idw;*.ipt) | *.iam;*.dwg;*.idw;*ipt | All files (*.*)|*.*"
	oFDlg.MultiSelectEnabled = False : oFDlg.OptionsEnabled = False
	oFDlg.InsertMode = False: oFDlg.CancelError = True
	Try : If bSave = True Then : oFDlg.ShowSave : Else : oFDlg.ShowOpen : End If : Catch : End Try
	Return oFDlg.FileName
End Function

Sub RecurseFileDescriptors(oFileDescs As FileDescriptorsEnumerator, FileDescriptorProcess As Action(Of Inventor.FileDescriptor))
	If oFileDescs Is Nothing OrElse oFileDescs.Count = 0 Then Return
	For Each oFD As Inventor.FileDescriptor In oFileDescs
		FileDescriptorProcess(oFD)
		Dim oChildFDs As FileDescriptorsEnumerator = Nothing
		If oFD.ReferencedFile IsNot Nothing Then
			Try : oChildFDs = oFD.ReferencedFile.ReferencedFileDescriptors : Catch : End Try
			If oChildFDs IsNot Nothing AndAlso oChildFDs.Count > 0 Then
				RecurseFileDescriptors(oChildFDs, FileDescriptorProcess)
			End If
		End If
	Next
End Sub

Sub ProcessFileDescriptor(oFD As Inventor.FileDescriptor)
	If oFD Is Nothing Then Return
	If oFD.ReferenceMissing OrElse oFD.ReferenceDisabled Then Return
	'<<< only process it if it is a part >>>
	If oFD.ReferencedFileType <> FileTypeEnum.kPartFileType Then Return
	Dim sFFN As String = oFD.FullFileName
	If sFFN = "" Then Return
	Dim sFileName As String = System.IO.Path.GetFileNameWithoutExtension(sFFN)
	Dim sExt As String = System.IO.Path.GetExtension(sFFN) 'includes the dot
	Dim sOldPrefix As String = "0980_"
	Dim sNewPrefix As String = "0970_"
	If Not sFileName.StartsWith(sOldPrefix) Then Return
	Dim sNewFileName As String = sFileName.Replace(sOldPrefix, sNewPrefix) & sExt
	Dim sNewFFN As String = sFFN.Replace(sFileName & sExt, sNewFileName)
	If System.IO.File.Exists(sNewFFN) Then
		'let user know about it
		Logger.Warn(vbCrLf & "The following file already existed:" & vbCrLf & _
		sNewFFN & vbCrLf & _
		"So, the following original file was not renamed:" & vbCrLf & sFFN)
	Else 'a file with the new name does not already exist, so rename it
		FileSystem.Rename(sFFN, sNewFFN)
		'now you may have to fix the file references referring to the old file name
		oFD.ReplaceReference(sNewFFN)
'		Logger.Info(vbCrLf & "The following 'original' file:" & vbCrLf & _
'		sFFN & vbCrLf & _
'		"was renamed to the following:" & vbCrLf & sNewFFN)
	End If
End Sub

If this solved your problem, or answered your question, please click ACCEPT SOLUTION .
Or, if this helped you, please click (LIKE or KUDOS) 👍.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 5 of 13
karram
in reply to: WCrihfield

Thanks for the guidelines,

I run this code into Assembly environment, then select source assembly file browser open, but its looks save mode. like below image.

 

karram_0-1713899420484.png

If i select the existing assembly and hits save button, no action takes place.

Then if i give new name, then its give error as below images

 

karram_1-1713899559229.png

 

Message 6 of 13
WCrihfield
in reply to: karram

I will have to look into it further tomorrow...on my way out now.

In Line 2, change 'True' to 'False' to have it use the 'Open' dialog, instead of 'Save'.

That dialog will not actually open or save anything, just returns the String, but only if you actually select an existing file, not just type something into the textbox.

If it still is not doing anything, then I will have to look at it more tomorrow.

Have a good evening.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 7 of 13
karram
in reply to: WCrihfield

hello,

 

It works but the main assembly asked the resolved link due to rename all parts in the folder. how this main assembly automatically assign the correct renaming parts like design assistant

 

Thanks

Message 8 of 13
Jacob__with__a__k
in reply to: karram

hi,

 

here to offer an alternative (but maybe unconventional)  solution: 

-check out all files that need to be renamed

-copy those files in windows explorer, in the same folder

   you are now left with '0980_xxxx.ipt'-files and '0980_xxxx - copy.ipt'-files

-rename all the '0980_xxxx - copy.ipt' - files to '0970_xxxx.ipt' (PowerRename is a good tool for this)

-now run this code in your assembly: (currently untested so don't use it on production files please)

it should replace all files that have "0980_" in the name with an almost identical named file at the same location

Dim oDoc As AssemblyDocument = ThisDoc.Document
Dim occs As ComponentOccurrences = oDoc.ComponentDefinition.Occurrences
Dim i, j, k, l As Integer
i = 0 : j = 0 : k = 0: l =0

For Each oPart As ComponentOccurrence In occs
	i += 1
	oPartFileName = oPart.Definition.Document.FullFileName
	oPartName = oPart.Name
	If oPartName.Contains("0980_")
		j +=1
		NewpartFilename = oPartFileName.Replace("0980_", "0970_")
		Try
			Component.Replace(oPartName, NewpartFilename, True)
			Logger.Trace("replaced " & oPartFileName & " with " & NewpartFilename)
			k+=1
		Catch
			Logger.Trace("failed to replace " & oPartFileName & " with " & NewpartFilename)
			l+=1
		End Try
		
	Else
	End If
Next

MessageBox.Show(i & " occurences in assembly" & vbCrLf & j & " '0980_' files found" & vbCrLf & k & " files replaced" & vbCrLf & l & " files failed to replace","Replacing parts")

 

-you should end up with only the '0970_xxxx.ipt'-files linked to your assembly and ready to check in in Vault

-the '0980_xxxx.ipt'-files will still be in your local and Vault folders, but since those are not linked anymore you are free to delete those

 

doesn't work for subassemblies tho, but should work in your specific case 🙂 

 

Happy coding!

Message 9 of 13
karram
in reply to: Jacob__with__a__k

Thanks,

while i run in an Assembly environment.

Error on line 8 in rule

oPartFileName = oPart.Definition.Document.FullFileName
Message 10 of 13
Jacob__with__a__k
in reply to: karram

Strange, its working for me... I did test that part of the code, just not the actual replacing...

 

That specific line gets the full path of the part, feel free to try a different method to get the full path, but I can't think of one atm

 

Without more info about the errormessage, when it throws the error, on which specific part, etc. I won't be able to help you fix this, since it's not throwing any errors for me...

gl

 

Happy coding!

 

 

Message 11 of 13
WCrihfield
in reply to: karram

Hi @karram.  My previous post included finding the old files, renaming them, and replacing the FileDescriptor references, but it lacked the additional step of replacing assembly components apparently.  This always confused me, because I do not use this type of process where I work.  It seems like using the FileDescriptor.ReplaceReference method should be all that is needed, but apparently not.  So, after expanding parts of my original code here to add more feedback when slightly unexpected things happen/found, I also added a 'Dictionary' collection in there, and a couple new routines to it (I know, its already pretty long).  The Dictionary is to keep track of the pairs of 'old' & 'new' full file names, as they are being renamed, so that we can use those in the assembly component replacement routine later.  One of the new routines is just for checking the originally selected full file name, to make sure it is not empty or contains any invalid path or file name characters, to avoid that possible situational error.  The other new routine is for the component replacement step.

This time, I will post the code in a text file (attached), because it is pretty long.  I still have not tested this yet though, because I have no use for something like this myself, so proceed with caution.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 12 of 13
WCrihfield
in reply to: karram

Also, in @Jacob__with__a__k code, instead of using this:

oPartFileName = oPart.Definition.Document.FullFileName

...where the 'oPart' variable represents a ComponentOccurrence object, try using this:

oPartFileName = oPart.ReferencedDocumentDescriptor.FullDocumentName

If any ComponentOccurrence is Suppressed, it will throw an error when you attempt to access its Definition.  Plus, if the ComponentOccurrence represents a 'virtual' component (for BOM use only), or it represents the 'welds' in a weldment type assembly, it may not have a Document, or a FullFileName.  There are ways to avoid those, if those are included in your assembly.  However, I believe going the ReferencedDocumentDescriptor route will still work even if the component is suppressed.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 13 of 13
karram
in reply to: WCrihfield

Works perfectly

Thanks for the guidelines

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk Design & Make Report