ScriptForge.FileSystem service

The FileSystem service includes routines to handle files and folders. Next are some examples of the features provided by this service:

note

The methods in the FileSystem service are mostly based on the XSimpleFileAccess UNO interface.


Definiciones

The table below lists the main parameters used by most of the methods in the FileSystem service.

Parámetro

Descripción

FileName

El nombre completo del archivo, la ruta incluida, sin esta incluir el separador de ruta al final.

FolderName

El nombre completo de la carpeta, ruta incluida, con o sin el separador de ruta final.

Name

The last component of the Folder Name or File Name including its extension. This parameter is always expressed using the native format of the operating system.

BaseName

The last component of the Folder Name or File Name without its extension.

NamePattern

Any of the above names containing wildcards in its last component. Admitted wildcards are:

  • «?» representa cualquier carácter individual

  • «*» representa cero, uno o múltiples caracteres


tip

The FileSystem service allows to perform operations over multiple files at the same time. By using name patterns, user scripts can copy, move or delete multiple files. Conversely, Basic built-in methods can only handle single files.


File Naming Notation

The notation used to express file and folder names, both for arguments and returned values, is defined by the FileNaming property of the FileSystem service.

In short, the possible representation types are "URL" (URL file notation), "SYS" (operating system notation) and "ANY" (default). See more information below.

tip

Un ejemplo de notación de URL es file:///C:/Documents/mi_archivo.odt. Considere, siempre que sea posible, utilizar la notación de URL, dado que es una alternativa más portátil.


Invocación del servicio

Before using the FileSystem service the ScriptForge library needs to be loaded using:


        GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
      

The following code snippet invokes the FileSystem service. The method BuildPath was used as an example.


      Dim FSO As Variant
      FSO = CreateScriptService("FileSystem")
      FSO.BuildPath(...)
    
note

This service is fully supported in both Basic and Python languages. All examples are expressed using the Basic programming language and can be easily converted to Python.


Propiedades

Nombre

De solo lectura

Tipo

Descripción

FileNaming

No

String

Establece o devuelve la notación actual de archivos y carpetas, la cual puede ser «ANY», «URL» o «SYS»:

  • "ANY": (default) the methods of the FileSystem service accept both URL and current operating system's notation for input arguments but always return URL strings.

  • "URL": the methods of the FileSystem service expect URL notation for input arguments and return URL strings.

  • "SYS": the methods of the FileSystem service expect current operating system's notation for both input arguments and return strings.

Once set, the FileNaming property remains unchanged either until the end of the LibreOffice session or until it is set again.

ConfigFolder

String

Devuelve la carpeta de configuración de LibreOffice.

ExtensionsFolder

String

Devuelve la carpeta en que se instalan las extensiones.

HomeFolder

String

Devuelve la carpeta personal del usuario.

InstallFolder

String

Devuelve la carpeta de instalación de LibreOffice.

TemplatesFolder

String

Devuelve la carpeta que contiene los archivos de plantillas de sistema.

TemporaryFolder

String

Devuelve la carpeta de archivos temporales definida en la configuración de rutas de LibreOffice.

UserTemplatesFolder

Yes

String

Returns the folder containing the user-defined template files.


Lista de métodos en el servicio FileSystem

BuildPath
CompareFiles
CopyFile
CopyFolder
CreateFolder
CreateTextFile
DeleteFile
DeleteFolder
FileExists

Files
FolderExists
GetBaseName
GetExtension
GetFileLen
GetFileModified
GetName
GetParentFolderName

GetTempName
HashFile
MoveFile
MoveFolder
OpenTextFile
PickFile
PickFolder
SubFolders


BuildPath

Joins a folder path and the name of a file and returns the full file name with a valid path separator. The path separator is added only if necessary.

Sintaxis:


        FSO.BuildPath(FolderName As String, Name As String) As String
    

Parámetros:

FolderName: The path with which Name will be combined. The specified path does not need to be an existing folder.

Name: The name of the file to be appended to FolderName. This parameter uses the notation of the current operating system.

Ejemplo:


      Dim FSO : FSO = CreateScriptService("FileSystem")
      FSO.FileNaming = "URL"
      MsgBox FSO.BuildPath("file:///home/user", "sample file.odt")
      'file:///home/user/sample%20file.odt
    

CompareFiles

Compares two files and returns True when they seem identical.

Depending on the value of the CompareContents argument, the comparison between both files can be either based only on file attributes (such as the last modified date), or based on the file contents.

Sintaxis:


          FSO.CompareFiles(FileName1 As String, FileName2 As String, [CompareContents As Boolean]) As Boolean
      

Parámetros:

FileName1, FileName2: The files to compare.

CompareContents: When True, the contents of the files are compared (default = False).

Ejemplo:


        FSO.FileNaming = "SYS"
        If FSO.CompareFiles("C:\myFile1.txt", "C:\myFile2.txt", CompareContents := False) Then
            ...
        End If
      

CopyFile

Copies one or more files from one location to another. Returns True if at least one file has been copied or False if an error occurred.

An error will also occur if the Source parameter uses wildcard characters and does not match any files.

El método se para inmediatamente después de que encuentra un error. El método no se revierte ni se deshacen los cambios efectuados antes de ocurrir el error.

Sintaxis:


        FSO.CopyFile(Source As String, Destination As String, [Overwrite As Boolean]) As Boolean
    

Parámetros:

Source: It can be a FileName or a NamePattern indicating one or more files to be copied.

Destination: It can be either a FileName specifying where the single Source file is to be copied, or a FolderName into which the multiple files from Source are to be copied.

Overwrite: If True (default), files may be overwritten. The method will fail if Destination is readonly, regardless of the value specified in Overwrite.

Ejemplo:


        FSO.FileNaming = "SYS"
        ' Copia un único archivo
        FSO.CopyFile("C:\Documents\my_file.odt", "C:\Temp\copied_file.odt")
        ' Copia varios archivos. Solamente se copian archivos, no las subcarpetas.
        FSO.CopyFile("C:\Documents\*.*", "C:\Temp\", Overwrite := False)
    

CopyFolder

Copies one or more folders from one location to another. Returns True if at least one folder has been copied or False if an error occurred.

An error will also occur if the Source parameter uses wildcard characters and does not match any folders.

El método se para inmediatamente después de que encuentra un error. El método no se revierte ni se deshacen los cambios efectuados antes de ocurrir el error.

Sintaxis:


        FSO.CopyFolder(Source As String, Destination As String, [Overwrite As Boolean]) As Boolean
    

Parámetros:

Source: It can be a FolderName or a NamePattern indicating one or more folders to be copied.

Destination: Specifies the FolderName into which the single or multiple folders defined in Source are to be copied.

Overwrite: If True (default), files may be overwritten. The method will fail if Destination is readonly, regardless of the value specified in Overwrite.

Ejemplo:


        FSO.FileNaming = "SYS"
        FSO.CopyFolder("C:\Documents\*", "C:\Temp\", Overwrite := False)
        ' Folders, their files and their subfolders are copied
    

CreateFolder

Creates the specified FolderName. Returns True if the folder could be successfully created.

If the specified folder has a parent folder that does not exist, it is created.

Sintaxis:


        FSO.CreateFolder(FolderName As String) As Boolean
    

Parámetros:

FolderName: A string representing the folder to be created. If the folder already exists, an exception will be raised.

Ejemplo:


        FSO.FileNaming = "SYS"
        FSO.CreateFolder("C:\NewFolder\")
    

CreateTextFile

Creates a specified file and returns a TextStream object that can be used to write to the file.

The method returns a Null object if an error occurred.

Sintaxis:


        FSO.CreateTextFile(FileName As String, [Overwrite As Boolean], [Encoding As String]) As Object
    

Parámetros:

FileName: The name of the file to be created.

Overwrite: Boolean value that determines if FileName can be overwritten (default = True).

Encoding: The character set to be used. The default encoding is "UTF-8".

Ejemplo:


        Dim myFile As Object
        FSO.FileNaming = "SYS"
        Set myFile = FSO.CreateTextFile("C:\Temp\ThisFile.txt", Overwrite := True)
    
note

To learn more about the names of character sets, visit IANA's Character Set page. Beware that LibreOffice does not implement all existing character sets.


DeleteFile

Deletes one or more files. Returns True if at least one file has been deleted or False if an error occurred.

An error will also occur if the FileName parameter uses wildcard characters and does not match any files.

The files to be deleted must not be readonly.

El método se para inmediatamente después de que encuentra un error. El método no se revierte ni se deshacen los cambios efectuados antes de ocurrir el error.

Sintaxis:


        FSO.DeleteFile(FileName As String) As Boolean
    

Parámetros:

FileName: It can be a FileName or a NamePattern indicating one or more files to be deleted.

Ejemplo:


        FSO.FileNaming = "SYS"
        FSO.DeleteFile("C:\Temp\*.docx")
        ' Only files are deleted, subfolders are not
    

DeleteFolder

Deletes one or more folders. Returns True if at least one folder has been deleted or False if an error occurred.

An error will also occur if the FolderName parameter uses wildcard characters and does not match any folders.

Las carpetas que se eliminarán no deben ser de solo lectura.

El método se para inmediatamente después de que encuentra un error. El método no se revierte ni se deshacen los cambios efectuados antes de ocurrir el error.

Sintaxis:


        FSO.DeleteFolder(FolderName As String) As Boolean
    

Parámetros:

FolderName: It can be a FolderName or a NamePattern indicating one or more folders to be deleted.

Ejemplo:


        FSO.FileNaming = "SYS"
        FSO.DeleteFolder("C:\Temp\*")
        ' Only folders are deleted, files in the top folder (C:\Temp\) are not
    

FileExists

Devuelve True si un nombre de archivo indicado es válido y existe; si no, el método devuelve False.

If the FileName parameter is actually an existing folder name, the method returns False.

Sintaxis:


        FSO.FileExists(FileName As String) As Boolean
    

Parámetros:

FileName: A string representing the file to be tested.

Ejemplo:


        FSO.FileNaming = "SYS"
        If FSO.FileExists("C:\Documents\my_file.odt") Then
            '...
        End If
    

Files

Returns a zero-based array of the files stored in a given folder. Each entry in the array is a string containing the full path and file name.

If FolderName does not exist, an exception is raised.

The resulting list may be filtered with wildcards.

Sintaxis:


        FSO.Files(FolderName As String, [Filter As String]) As Variant
    

Parámetros:

FolderName: A string representing a folder. The folder must exist. FolderName must not designate a file.

Filter: A string containing wildcards ("?" and "*") that will be applied to the resulting list of files (default = "").

Ejemplo:


        Dim filesList As Variant, file As String
        FSO.FileNaming = "SYS"
        filesList = FSO.Files("/home/user/", "*.txt")
        For Each file In filesList
            ' ...
        Next file
    

FolderExists

Devuelve True si el FolderName especificado es válido y existe; si no, el método devuelve False.

If the FolderName parameter is actually an existing file name, the method returns False.

Sintaxis:


        FSO.FolderExists(FolderName As String) As Boolean
    

Parámetros:

FolderName: A string representing the folder to be tested.

Ejemplo:


        FSO.FolderNaming = "SYS"
        If FSO.FolderExists("C:\Documents\Thesis") Then
            '...
        End If
    

GetBaseName

Returns the BaseName (equal to the last component) of a folder or file name, without its extension.

El método no comprueba si existe el archivo o la carpeta que se especificó.

Sintaxis:


        FSO.GetBaseName(FileName As String) As String
    

Parámetros:

FileName: A string representing the file name and its path.

Ejemplo:


        ' If the input parameter is a folder, it returns the last component of the path
        MsgBox FSO.GetBaseName("/home/user/Documents") ' "Documents"
        ' If the input parameter is a file, the method returns the file name without the extension and the path
        MsgBox FSO.GetBaseName("/home/user/Documents/my_file.ods") ' "my_file"
    

GetExtension

Returns the extension part of a file or folder name without the dot "." character.

El método no comprueba la existencia del archivo o la carpeta que se haya especificado.

If this method is applied to a folder name or to a file without an extension, then an empty string is returned.

Sintaxis:


        FSO.GetExtension(FileName As String) As String
    

Parámetros:

FileName: A string representing the file name and its path.

Ejemplo:


        FSO.FileNaming = "SYS"
        MsgBox FSO.GetExtension("C:\Windows\Notepad.exe")  ' "exe"
    

GetFileLen

The builtin FileLen Basic function returns the number of bytes contained in a file as a Long value, i.e. up to 2GB.

The GetFileLen method can handle files with much larger sizes by returning a Currency value.

Sintaxis:


        FSO.GetFileLen(FileName As String) As Currency
    

Parámetros:

FileName: A string representing an existing file.

Ejemplo:


        Dim a As Currency
        FSO.FileNaming = "SYS"
        a = FSO.GetFileLen("C:\pagefile.sys")
    

GetFileModified

Devuelve la fecha de última modificación de un archivo determinado.

Sintaxis:


        FSO.GetFileModified(FileName As String) As Date
    

Parámetros:

FileName: A string representing an existing file.

Ejemplo:


        Dim a As Date
        FSO.FileNaming = "SYS"
        a = FSO.GetFileModified("C:\Documents\my_file.odt")
    

GetName

Returns the last component of a file or folder name in native operating system format.

El método no comprueba si existe el archivo o la carpeta que se especificó.

Sintaxis:


        FSO.GetName(FileName As String) As String
    

Parámetros:

FileName: A string representing the file name and its path.

Ejemplo:


        Dim a As String
        FSO.FileNaming = "SYS"
        a = FSO.GetName("C:\Windows\Notepad.exe"  ' Notepad.exe
    

GetParentFolderName

Returns a string containing the name of the parent folder of a specified file or folder name.

El método no comprueba si existe el archivo o la carpeta que se especificó.

Sintaxis:


        FSO.GetParentFolderName(FileName As String) As String
    

Parámetros:

FileName: A string with the file or folder name to be analyzed.

Ejemplo:


        Dim a As String
        FSO.FileNaming = "SYS"
        a = FSO.GetParentFolderName("C:\Windows\Notepad.exe"  ' C:\Windows\
    

GetTempName

Returns a randomly generated temporary file name that is useful for performing operations that require a temporary file.

The returned file name does not have any suffix. The folder part of the returned string is the system's temporary folder.

El método no crea el archivo temporal.

Sintaxis:


        FSO.GetTempName() As String
    

Ejemplo:


        Dim a As String
        FSO.FolderNaming = "SYS"
        a = FSO.GetTempName() & ".txt"
        ' "/tmp/SF_574068.txt"
    

HashFile

Hash functions are used by some cryptographic algorithms, in digital signatures, message authentication codes, fraud detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more.

The HashFile method returns the result of a hash function, applied on a given file and using a specified algorithm. The returned value is a string of lower-case hexadecimal digits.

The hash algorithms supported are: MD5, SHA1, SHA224, SHA256, SHA384 and SHA512.

Sintaxis:


        FSO.HashFile(FileName As String, Algorithm As String) As String
    

Parámetros:

FileName: A string representing an existing file.

Algorithm: One of the supported algorithms.

Ejemplo:


        FSO.FileNaming = "SYS"
        MsgBox FSO.HashFile("C:\pagefile.sys", "MD5")
    

MoveFile

Moves one or more files from one location to another. Returns True if at least one file has been moved or False if an error occurred.

An error will also occur if the Source parameter uses wildcard characters and does not match any files.

El método se para inmediatamente después de que encuentra un error. El método no se revierte ni se deshacen los cambios efectuados antes de ocurrir el error.

Sintaxis:


        FSO.MoveFile(Source As String, Destination As String) As Boolean
    

Parámetros:

Source: It can be a FileName or NamePattern to designate one or more files to be moved.

Destination: If Source is a FileName then this parameter indicates the new path and file name of the moved file.

If the move operation involves multiple files, then Destination must be a folder name. If it does not exist, it is created.

If Source and Destination have the same parent folder, the method will rename the Source.

Wildcard characters are not allowed in Destination.

Ejemplo:


        Dim a As String
        FSO.FileNaming = "SYS"
        FSO.MoveFile("C:\Temp1\*.*", "C:\Temp2\")
        ' Only files are moved, subfolders are not
    

MoveFolder

Moves one or more folders from one location to another. Returns True if at least one folder has been moved or False if an error occurred.

An error will also occur if the Source parameter uses wildcard characters and does not match any folders.

El método se para inmediatamente después de que encuentra un error. El método no se revierte ni se deshacen los cambios efectuados antes de ocurrir el error.

Sintaxis:


        FSO.MoveFolder(Source As String, Destination As String) As Boolean
    

Parámetros:

Source: It can be a FolderName or NamePattern to designate one or more folders to be moved.

Destination: If the move operation involves a single folder, then Destination is the name and path of the moved folder and it must not exist.

If multiple folders are being moved, then Destination designates where the folders in Source will be moved into. If Destination does not exist, it is created.

Wildcard characters are not allowed in Destination.

Ejemplo:


        Dim a As String
        FSO.FileNaming = "SYS"
        FSO.MoveFolder("C:\Temp1\*", "C:\Temp2\")
    

OpenTextFile

Opens a file and returns a TextStream object that can be used to read from, write to, or append to the file.

Observe que el método no comprueba que el archivo indicado realmente sea de texto.

The method returns a Null object if an error occurred.

Sintaxis:


        FSO.OpenTextFile(FileName As String, [IOMode As Integer], [Create As Boolean], [Encoding As String]) As Object
    

Parámetros:

FileName: Identifies the file to open.

IOMode: Indicates the input/output mode. It can be one of three constants: FSO.ForReading (default), FSO.ForWriting, or FSO.ForAppending.

Create: Boolean value that indicates whether a new file can be created if the specified filename doesn't exist:

Encoding: The character set to be used. The default encoding is "UTF-8".

Ejemplo:


        Dim myFile As Object
        FSO.FileNaming = "SYS"
        Set myFile = FSO.OpenTextFile("C:\Temp\ThisFile.txt", FSO.ForReading)
        If Not IsNull(myFile) Then
            ' ...
        End If
    

PickFile

Abre un cuadro de diálogo para abrir o guardar archivos.

If the SAVE mode is set and the picked file exists, a warning message will be displayed.

Sintaxis:


      FSO.PickFile([DefaultFile As String], [Mode As String], [Filter As String]) As String
    

Parámetros:

DefaultFile: This argument is a string composed of a folder and file name:

Mode: OPEN (input file) or SAVE (output file). The default value is OPEN.

Filter: The extension of the files displayed when the dialog is opened (default = no filter).

Ejemplo:


        Dim a As Variant
        FSO.FileNaming = "SYS"
        a = FSO.PickFile("C:\", "OPEN", "txt")
        ' Solo se muestran los archivos *.txt
    

PickFolder

Abre un cuadro de diálogo para seleccionar una carpeta.

Sintaxis:


        FSO.PickFolder([DefaultFolder As String], [FreeText As String]) As String
    

Parámetros:

DefaultFolder: A string containing the folder name that will be displayed when the dialog is opened (default = the last selected folder).

FreeText: Text to display in the dialog (default = "").

Ejemplo:


        Dim a As Variant
        FSO.FileNaming = "SYS"
        a = FSO.PickFolder("C:\", "Elija una carpeta o pulse en Cancelar")
    

SubFolders

Returns a zero-based array of the folders stored in a given FolderName.

La lista puede filtrarse por medio de comodines.

Sintaxis:


        FSO.SubFolders(FolderName As String, [Filter As String]) As Variant
    

Parámetros:

FolderName: A string representing a folder. The folder must exist. FolderName must not designate a file.

Filter: A string containing wildcards ("?" and "*") that will be applied to the resulting list of folders (default = "").

Ejemplo:


        Dim folderList As Variant, folder As String
        FSO.FileNaming = "SYS"
        folderList = FSO.SubFolders("/home/user/")
        For Each folder In folderList
            ' ...
        Next folder
    
warning

Todas las rutinas o los identificadores Basic de ScriptForge que comienzan por un guion bajo «_» son únicamente para uso interno. No deben utilizarse en macros Basic.


¡Necesitamos su ayuda!