Home > The CATIA Object Model > Using file open and save dialogs

Using file open and save dialogs

February 8, 2010 Leave a comment Go to comments

Many programming projects require the user of the program to specify either a file to open or save.  That file could be anything from a native CATIA file such as a CATPart or CATDrawing to a simple text file.  Luckily, the CATIA automation API provides methods to display familiar file dialogs just like those you see in any other Windows application.  In this article I will show how easy they are to incorporate into your programming project and also how to deal with some common file related issues.

Overview

The ability to display these dialogs is made possible by the FileSelectionBox method provided by the CATIA Application object.  Realize that when the user selects a file using this method, it only returns a string indicating the full path of the file.  It does not actually open or save a file.  This gives you the flexibility to use these dialogs for many different purposes, file types and applications. The general syntax looks like this,

strFilePath = CATIA.FileSelectionBox(iTitle, iExtension, iMode)

There are three input arguments and a return value as described below:

iTitle – The text to display in the title bar of the dialog

iExtension – The file extensions allowed (sets the filter at the bottom of the dialog)

iMode – The type of dialog to display (CatFileSelectionModeOpen = 0, CatFileSelectionModeSave = 1)

strFilePath – The full file path selected or empty string (“”) if Cancel was clicked

Example 1: Open

Let’s assume you are creating a program that needs to read a comma-separated value (csv) file to get some input values for your program.  You want to first prompt the user to browse and select a file having this format, then read in the values to use in the program.

Dim strFilePath As String
Dim objFile As File
Dim objTextStream As TextStream
Dim strLine As String

'Display file open dialog
strFilePath = CATIA.FileSelectionBox("Select Text File", "*.txt, *.csv", 0)

'If user clicked cancel (empty string is returned), then exit the program
If strFilePath = "" Then Exit Sub

'Open the file, read the first line then close the file
Set objFile = CATIA.FileSystem.GetFile(strFilePath)
Set objTextStream = objFile.OpenAsTextStream("ForReading")
strLine = objTextStream.ReadLine
objTextStream.Close

'Display the read text value…just to show it was read.
Msgbox "First line: " &strLine, 0, "Text File Content"

The result will be something like this,

Example 2: Save

In this example, let’s assume your program has just built a new CATPart and now you want to have the user specify a file folder and name for it to be saved.

Dim objBody As Body
Dim objDoc As Document
Dim strFilePath As String
Dim strMsg As String

'Create a new part and add a new body
Set objDoc = CATIA.Documents.Add("Part")
Set objBody = objDoc.Part.Bodies.Add
objBody.Name = "Body generated by automation!"

'Prompt user for where to save the new part
strFilePath = CATIA.FileSelectionBox("SaveAs", "*.CATPart", 0)

'If user clicked cancel (empty string is returned), then exit the program
If strFilePath = "" Then
  strMsg = "Save operation was cancelled, so the new part will not be saved!"
  Msgbox strMsg, 48, "File Not Saved"
  Exit Sub
End If

'Save the part
objDoc.SaveAs strFilePath

The result will be something like this,

Don’t assume the returned file path is valid

After you make a call to the FileSelectionBox method, you should always check the return value before trying to use it in any downstream open or save operation.   Below, I will show a few common situations that occur with file operations.

Handling a cancel click by the user

If the user clicked Cancel, the returned file path will be an empty string.  You should always detect this and display some message or maybe even immediately end the program.

For example,

Dim strFilePath As String

strFilePath = CATIA.FileSelectionBox("SaveAs", "*.CATPart", 0)
If strFilePath = "" Then
   strMsg = "File selection was cancelled, so the program will end."
   Msgbox strMsg, 64, "Program End"
   Exit Sub
End If

Catching a save error

For a save operation, you will likely want to check to see whether the save was successful.  This way you can notify the user of a problem rather than allowing your program to crash.

Expanding the previous example a bit we get:

'For this example, assume a CATPart is currently open

Dim strFilePath As String

strFilePath = CATIA.FileSelectionBox("SaveAs", "*.CATPart", 0)
If strFilePath = "" Then
   strMsg = "File selection was cancelled, so the program will end."
   Msgbox strMsg, 64, "Program End"
   Exit Sub
Else
   'Try to save
   On Error Resume Next
   CATIA.ActiveDocument.SaveAs strFilePath
   If Err.Number <> 0 Then   'Any value other than zero is an error
      Msgbox "A save error occurred.  Program will end.", 64, "Save Error"
      Exit Sub
   Else
      'Reset error handler
      On Error Goto 0
   End If
End If

Checking write permission

If you want to go a step further, you may want to confirm that the user has write permission to the selected path.  Why not just check for an error and notify the user that an error occurred?  Whenever you can, it’s best to give the user an accurate assessment of the problem so they can attempt to resolve it rather than leaving them confused.  For example, you might be able to detect a permissions problem as opposed to some other problem such as running out of disk space.  Then you could prompt them try to select a different file path.

Checking write permission can sometimes be accomplished by querying the folder permissions in Windows, but honestly this can be very tricky.  This is especially true on a networked file system with group permissions.  I have found that the easiest way is to simply test whether a file can be written to the specified folder.

Again adding to the previous example we get,

'For this example, assume a CATPart is currently open

Dim strFilePath As String
Dim intPos As Integer
Dim strFolder As String
Dim objFile As File

strFilePath = CATIA.FileSelectionBox("SaveAs", "*.CATPart", 0)
If strFilePath = "" Then
   Msgbox "File selection was cancelled, so the program will end.", 64, "Program End"
   Exit Sub
Else
   'First we need to get just the folder path of the selected file
   'Find the position of the last \ character
   intPos = InStrRev(strFilePath, "\")   
   'Get the portion of string up to last \ character
   strFolder = Left(strFilePath, intPos)   

   'Test write permission by writing a test file in this folder
   On Error Resume Next
   Set objFile = CATIA.FileSystem.CreateFile(strFolder &"\1A2B3C4D5E.txt",false)
   If Err.Number <> 0 Then
      strMsg = "File could not be saved to this location.  Please check"
      strMsg = strMsg &"that you have permission to save to this folder…"
      Msgbox strMsg, 64, “Save Error”
      Exit Sub
   Else
      'Delete the test file if the save was successful
      CATIA.DeleteFile strFolder &"\1A2B3C4D5E.txt”
      'Reset error handler
      On Error Goto 0
   End If

   'Try to save the actual document
   On Error Resume Next
   CATIA.ActiveDocument.SaveAs strFilePath
   If Err.Number <> 0 Then
      strMsg = "An unknown save error occurred." &vbCrLf &"Check disk space, etc…"
      Msgbox strMsg, 64, "Save Error"
      Exit Sub
   Else
      On Error Goto 0
   End If
End If

Advanced options for file and folder browsing

These two dialogs should meet your needs for nearly all open and save tasks.  However, if you need to further customize these dialogs or if you need a folder selection dialog box, you will need to use the WinAPI.  In this case, your project will need to be done in VBA or outside CATIA using any language that supports COM and allows you to declare and call a WinAPI.  This is supported in VB6, any of the .NET languages, and many others.  Unfortunately, you cannot make calls to the WinAPI from CATIA V5 scripts. I did a quick google search and found some code for a BrowseFolder dialog here.

Please take a moment to rate this article…Just click the stars up near the title.

Add to: del.icio.us del.icio.us, StumbleUpon StumbleUpon, Digg Digg, Google Google

Advertisements
  1. Julian50
    February 11, 2010 at 3:23 pm

    Very nice explications. Finally I found the website that I wanted about catia v5 and VBA. Thanks a lot.Looking forward for next explications!

  2. February 12, 2010 at 1:12 am

    Thank you for this blog, i will follow you

  3. Jverne
    February 23, 2011 at 3:52 am

    Great post. It was very useful for me.

  4. ben
    May 2, 2011 at 4:20 am

    He, does anyone know if it is possible to insert a second body into an active document from an earlier created file. So i have one partbody, and i would like to insert another one from a different file. Any suggestions?

    Thanks

    • May 2, 2011 at 7:40 pm

      Hi Ben – Copy-Paste using the selection object is probably your best bet and just like when you copy-paste interactively, you can choose as specified, with link, etc. I can give you some code if you can share more details of the scenario (Is the other file open, do you want to select the body in the other document then select the destination body in the 2nd document, etc.)

  5. Nick
    June 7, 2011 at 6:19 pm

    I’m not sure if it’s just me or my machine/version etc, but think that first example has a typo. To allow the open dialog to allow multiple file types the file types string should be semi-colon delineated. The result shows a semi-colon in the Files of Type field, but the example had a comma.

    ‘Display file open dialog
    strFilePath = CATIA.FileSelectionBox(“Select Text File”, “*.txt; *.csv”, 0)

    Thanks so much for the help!

    • June 9, 2011 at 10:26 pm

      Hi Nick – you are right about the semicolon, sorry for the typo.

  6. Bjorn
    September 5, 2011 at 7:25 am

    Hello.
    This is a very nice description and leaves not a lot for own imagination, in a good way :)
    I just have a question about the saving part. Can I decide to automatically save the file without enter filename and left-click on the save button?! I would like to create a loop and after each iteration save a file. (I will remove it again directly so the filename can be the same every loop)

    Thank you in advance..

  7. Bjorn
    September 5, 2011 at 9:38 am

    ok, I’m not very good in all the coding but I found a solution that works good for me for the moment..

    Set partDocument1 = CATIA.ActiveDocument

    Set part1 = partDocument1.Part

    part1.Update

    % To just save the file without open the textdialog.
    partDocument1.SaveAs “C:\Users\Bear\Desktop\test.CATPart”

    I just recorded a macro to find the solution, sometimes we have to think twice and often the easiest solution is the best one!

    Keep up the good work!

  8. J.Kress
    February 22, 2012 at 6:44 pm

    Thank you so much for taking the time to share this information. Most helpful and you saved me a great deal of time. Thanks again.

  9. Billy
    April 27, 2012 at 4:11 pm

    Anyone know how to multiselect files with the CATIA fileselectionbox or any other method ?

  10. March 7, 2013 at 6:43 am

    Great but one thing is missing…If i want to initialize browse box with some value then its impossible.

  1. No trackbacks yet.

Leave a Reply to Julian50 Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: