1 <?xml version=
"1.0" encoding=
"UTF-8"?>
2 <!DOCTYPE script:module PUBLIC
"-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
3 <script:module xmlns:
script=
"http://openoffice.org/2000/script" script:
name=
"SF_FileSystem" script:
language=
"StarBasic" script:
moduleType=
"normal">REM =======================================================================================================================
4 REM === The ScriptForge library and its associated libraries are part of the LibreOffice project. ===
5 REM === Full documentation is available on https://help.libreoffice.org/ ===
6 REM =======================================================================================================================
11 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
12 ''' SF_FileSystem
13 ''' =============
14 ''' Class implementing the file system service
15 ''' for common file and folder handling routines
16 ''' Including copy and move of files and folders, with or without wildcards
17 ''' The design choices are largely inspired by
18 ''' https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/filesystemobject-object
19 ''' The File and Folder classes have been found redundant with the current class and have not been implemented
20 ''' The implementation is mainly based on the XSimpleFileAccess UNO interface
21 ''' https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1ucb_1_1XSimpleFileAccess.html
23 ''' Subclasses:
24 ''' SF_TextStream
26 ''' Definitions:
27 ''' File and folder names may be expressed either in the (preferable because portable) URL form
28 ''' or in the more usual operating system notation (e.g. C:\... for Windows)
29 ''' The notation, both for arguments and for returned values
30 ''' is determined by the FileNaming property: either
"ANY
" (default),
"URL
" or
"SYS
"
32 ''' FileName: the full name of the file including the path without any ending path separator
33 ''' FolderName: the full name of the folder including the path and the ending path separator
34 ''' Name: the last component of the File- or FolderName including its extension
35 ''' BaseName: the last component of the File- or FolderName without its extension
36 ''' NamePattern: any of the above names containing wildcards in its last component
37 ''' Admitted wildcards are: the
"?
" represents any single character
38 ''' the
"*
" represents zero, one, or multiple characters
40 ''' Disk file systems and document
's internal file systems
41 ''' All the implemented properties and methods are applicable on usual disk file systems.
42 ''' Root is usually something like
"C:\
" or
"/
" or their URL equivalents
43 ''' Now, Libreoffice documents have an internal file system as well. Many of the proposed methods
44 ''' support document
's file systems too, however, for some of them, with restrictions.
45 ''' Read the comments in the individual methods below.
46 ''' It makes browsing folders and files, adding, replacing files possible. Updates will be
47 ''' saved with the document.
48 ''' VERY POWERFUL but KNOW WHAT YOU
'RE DOING !!
49 ''' The root of a document
's file system is obtained from the
"FileSystem
" property of a document instance, like in:
50 ''' Dim root As String, doc As Object, ui As Object
51 ''' Set ui = CreateScriptService(
"ui
")
52 ''' Set doc = ui.GetDocument(ThisComponent)
53 ''' root = doc.FileSystem
54 ''' The file manifest.xml is managed automatically.
55 ''' The FileNaming setting is ignored.
57 ''' Service invocation example:
58 ''' Dim FSO As Variant
59 ''' Set FSO = CreateScriptService(
"FileSystem
")
61 ''' Detailed user documentation:
62 ''' https://help.libreoffice.org/latest/en-US/text/sbasic/shared/
03/sf_filesystem.html?DbPAR=BASIC
63 '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
65 REM ================================================================== EXCEPTIONS
67 Const UNKNOWNFILEERROR =
"UNKNOWNFILEERROR
" ' Source file does not exist
68 Const UNKNOWNFOLDERERROR =
"UNKNOWNFOLDERERROR
" ' Source folder or Destination folder does not exist
69 Const NOTAFILEERROR =
"NOTAFILEERROR
" ' Destination is a folder, not a file
70 Const NOTAFOLDERERROR =
"NOTAFOLDERERROR
" ' Destination is a file, not a folder
71 Const OVERWRITEERROR =
"OVERWRITEERROR
" ' Destination can not be overwritten
72 Const READONLYERROR =
"READONLYERROR
" ' Destination has its read-only attribute set
73 Const NOFILEMATCHERROR =
"NOFILEMATCHFOUND
" ' No file matches Source containing wildcards
74 Const FOLDERCREATIONERROR =
"FOLDERCREATIONERROR
" ' FolderName is an existing folder or file
75 Const FILESYSTEMERROR =
"FILESYSTEMERROR
" ' The method is not applicable on document
's file systems
77 REM ============================================================ MODULE CONSTANTS
79 ''' TextStream open modes
80 Const cstForReading =
1
81 Const cstForWriting =
2
82 Const cstForAppending =
8
84 ''' Document file system
85 Const DOCFILESYSTEM =
"vnd.sun.star.tdoc:/
"
87 ''' Folders and files scanning
88 Const cstSEPARATOR =
"//;
" ' Separates folders or files in the accumulators
89 Const cstFILES =
1 ' Caler = Files()
90 Const cstFOLDERS =
2 ' Caller = SubFolders()
92 REM ===================================================== CONSTRUCTOR/DESTRUCTOR
94 REM -----------------------------------------------------------------------------
95 Public Function Dispose() As Variant
97 End Function
' ScriptForge.SF_FileSystem Explicit destructor
99 REM ================================================================== PROPERTIES
101 REM -----------------------------------------------------------------------------
102 Property Get ConfigFolder() As String
103 ''' Return the configuration folder of LibreOffice
105 Const cstThisSub =
"FileSystem.getConfigFolder
"
107 SF_Utils._EnterFunction(cstThisSub)
108 ConfigFolder = SF_FileSystem._GetConfigFolder(
"user
")
109 SF_Utils._ExitFunction(cstThisSub)
111 End Property
' ScriptForge.SF_FileSystem.ConfigFolder
113 REM -----------------------------------------------------------------------------
114 Property Get ExtensionsFolder() As String
115 ''' Return the folder containing the extensions installed for the current user
117 Dim oMacro As Object
' /singletons/com.sun.star.util.theMacroExpander
118 Const cstThisSub =
"FileSystem.getExtensionsFolder
"
120 SF_Utils._EnterFunction(cstThisSub)
121 Set oMacro = SF_Utils._GetUNOService(
"MacroExpander
")
122 ExtensionsFolder = SF_FileSystem._ConvertFromUrl(oMacro.ExpandMacros(
"$UNO_USER_PACKAGES_CACHE
")
& "/
")
123 SF_Utils._ExitFunction(cstThisSub)
125 End Property
' ScriptForge.SF_FileSystem.ExtensionsFolder
127 REM -----------------------------------------------------------------------------
128 Property Get FileNaming() As Variant
129 ''' Return the current files and folder notation, either
"ANY
",
"URL
" or
"SYS
"
130 ''' "ANY
": methods receive either URL or native file names, but always return URL file names
131 ''' "URL
": methods expect URL arguments and return URL strings (when relevant)
132 ''' "SYS
": idem but operating system notation
134 Const cstThisSub =
"FileSystem.getFileNaming
"
135 SF_Utils._EnterFunction(cstThisSub)
136 FileNaming = _SF_.FileSystemNaming
137 SF_Utils._ExitFunction(cstThisSub)
139 End Property
' ScriptForge.SF_FileSystem.FileNaming (get)
141 REM -----------------------------------------------------------------------------
142 Property Let FileNaming(ByVal pvNotation As Variant)
143 ''' Set the files and folders notation:
"ANY
",
"URL
" or
"SYS
"
145 Const cstThisSub =
"FileSystem.setFileNaming
"
146 SF_Utils._EnterFunction(cstThisSub)
147 If VarType(pvNotation) = V_STRING Then
148 Select Case UCase(pvNotation)
149 Case
"ANY
",
"URL
",
"SYS
" : _SF_.FileSystemNaming = UCase(pvNotation)
150 Case Else
' Unchanged
153 SF_Utils._ExitFunction(cstThisSub)
155 End Property
' ScriptForge.SF_FileSystem.FileNaming (let)
157 REM -----------------------------------------------------------------------------
158 Property Get ForAppending As Integer
159 ''' Convenient constant (see documentation)
160 ForAppending = cstForAppending
161 End Property
' ScriptForge.SF_FileSystem.ForAppending
163 REM -----------------------------------------------------------------------------
164 Property Get ForReading As Integer
165 ''' Convenient constant (see documentation)
166 ForReading = cstForReading
167 End Property
' ScriptForge.SF_FileSystem.ForReading
169 REM -----------------------------------------------------------------------------
170 Property Get ForWriting As Integer
171 ''' Convenient constant (see documentation)
172 ForWriting = cstForWriting
173 End Property
' ScriptForge.SF_FileSystem.ForWriting
175 REM -----------------------------------------------------------------------------
176 Property Get HomeFolder() As String
177 ''' Return the user home folder
179 Const cstThisSub =
"FileSystem.getHomeFolder
"
181 SF_Utils._EnterFunction(cstThisSub)
182 HomeFolder = SF_FileSystem._GetConfigFolder(
"home
")
183 SF_Utils._ExitFunction(cstThisSub)
185 End Property
' ScriptForge.SF_FileSystem.HomeFolder
187 REM -----------------------------------------------------------------------------
188 Property Get InstallFolder() As String
189 ''' Return the installation folder of LibreOffice
191 Const cstThisSub =
"FileSystem.getInstallFolder
"
193 SF_Utils._EnterFunction(cstThisSub)
194 InstallFolder = SF_FileSystem._GetConfigFolder(
"inst
")
195 SF_Utils._ExitFunction(cstThisSub)
197 End Property
' ScriptForge.SF_FileSystem.InstallFolder
199 REM -----------------------------------------------------------------------------
200 Property Get ObjectType As String
201 ''' Only to enable object representation
202 ObjectType =
"SF_FileSystem
"
203 End Property
' ScriptForge.SF_FileSystem.ObjectType
205 REM -----------------------------------------------------------------------------
206 Property Get ServiceName As String
207 ''' Internal use
208 ServiceName =
"ScriptForge.FileSystem
"
209 End Property
' ScriptForge.SF_FileSystem.ServiceName
211 REM -----------------------------------------------------------------------------
212 Property Get TemplatesFolder() As String
213 ''' Return the folder defined in the LibreOffice paths options as intended for templates files
215 Dim sPath As String
' Template property of com.sun.star.util.PathSettings
216 Const cstThisSub =
"FileSystem.getTemplatesFolder
"
218 SF_Utils._EnterFunction(cstThisSub)
219 sPath = SF_Utils._GetUNOService(
"PathSettings
").Template
220 TemplatesFolder = SF_FileSystem._ConvertFromUrl(Split(sPath,
";
")(
0)
& "/
")
221 SF_Utils._ExitFunction(cstThisSub)
223 End Property
' ScriptForge.SF_FileSystem.TemplatesFolder
225 REM -----------------------------------------------------------------------------
226 Property Get TemporaryFolder() As String
227 ''' Return the folder defined in the LibreOffice paths options as intended for temporary files
229 Const cstThisSub =
"FileSystem.getTemporaryFolder
"
231 SF_Utils._EnterFunction(cstThisSub)
232 TemporaryFolder = SF_FileSystem._GetConfigFolder(
"temp
")
233 SF_Utils._ExitFunction(cstThisSub)
235 End Property
' ScriptForge.SF_FileSystem.TemporaryFolder
237 REM -----------------------------------------------------------------------------
238 Property Get UserTemplatesFolder() As String
239 ''' Return the folder defined in the LibreOffice paths options as intended for User templates files
241 Dim sPath As String
' Template_writable property of com.sun.star.util.PathSettings
242 Const cstThisSub =
"FileSystem.getUserTemplatesFolder
"
244 SF_Utils._EnterFunction(cstThisSub)
245 sPath = SF_Utils._GetUNOService(
"PathSettings
").Template_writable
246 UserTemplatesFolder = SF_FileSystem._ConvertFromUrl(sPath
& "/
")
247 SF_Utils._ExitFunction(cstThisSub)
249 End Property
' ScriptForge.SF_FileSystem.UserTemplatesFolder
251 REM ===================================================================== METHODS
253 REM -----------------------------------------------------------------------------
254 Public Function BuildPath(Optional ByVal FolderName As Variant _
255 , Optional ByVal Name As Variant _
257 ''' Combines a folder path and the name of a file and returns the combination with a valid path separator
258 ''' Inserts an additional path separator between the foldername and the name, only if necessary
259 ''' Args:
260 ''' FolderName: Path with which Name is combined. Path need not specify an existing folder
261 ''' Name: To be appended to the existing path.
262 ''' Returns:
263 ''' The path concatenated with the file name after insertion of a path separator, if necessary
264 ''' Example:
265 ''' Dim a As String
266 ''' FSO.FileNaming =
"SYS
"
267 ''' a = FSO.BuildPath(
"C:\Windows
",
"Notepad.exe
") returns C:\Windows\Notepad.exe
269 Dim sBuild As String
' Return value
270 Dim sFile As String
' Alias for Name
271 Const cstFileProtocol =
"file:///
"
272 Const cstThisSub =
"FileSystem.BuildPath
"
273 Const cstSubArgs =
"FolderName, Name
"
275 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
276 sBuild =
""
279 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
280 If Not SF_Utils._ValidateFile(FolderName,
"FolderName
") Then GoTo Finally
281 If Not SF_Utils._Validate(Name,
"Name
", V_STRING) Then GoTo Finally
283 FolderName = SF_FileSystem._ConvertToUrl(FolderName)
286 ' Add separator if necessary. FolderName is now in URL notation
287 If Len(FolderName)
> 0 Then
288 If Right(FolderName,
1)
<> "/
" Then sBuild = FolderName
& "/
" Else sBuild = FolderName
290 sBuild = cstFileProtocol
292 ' Encode the file name
293 sFile = ConvertToUrl(Name)
294 ' Some file names produce http://file.name.suffix/
295 If Left(sFile,
7) =
"http://
" Then sFile = cstFileProtocol
& Mid(sFile,
8, Len(sFile) -
8)
296 ' Combine both parts
297 If Left(sFile, Len(cstFileProtocol)) = cstFileProtocol Then sBuild = sBuild
& Mid(sFile, Len(cstFileProtocol) +
1) Else sBuild = sBuild
& sFile
300 BuildPath = SF_FileSystem._ConvertFromUrl(sBuild)
301 SF_Utils._ExitFunction(cstThisSub)
305 End Function
' ScriptForge.SF_FileSystem.BuildPath
307 REM -----------------------------------------------------------------------------
308 Public Function CompareFiles(Optional ByVal FileName1 As Variant _
309 , Optional ByVal FileName2 As Variant _
310 , Optional ByVal CompareContents As Variant _
312 ''' Compare
2 files and return True if they seem identical
313 ''' The comparison may be based on the file attributes, like modification time,
314 ''' or on their contents.
315 ''' The method is not supported for document
's internal file systems.
316 ''' Args:
317 ''' FileName1: The
1st file to compare
318 ''' FileName2: The
2nd file to compare
319 ''' CompareContents: When True, the contents of the files are compared. Default = False
320 ''' Returns:
321 ''' True when the files seem identical
322 ''' Exceptions:
323 ''' UNKNOWNFILEERROR One of the files does not exist
324 ''' FILESYSTEMERROR The method is not applicable on document
's file systems
325 ''' Example:
326 ''' FSO.FileNaming =
"SYS
"
327 ''' MsgBox FSO.CompareFiles(
"C:\myFile1.txt
",
"C:\myFile2.txt
", CompareContents := True)
329 Dim bCompare As Boolean
' Return value
330 Dim sFile As String
' Alias of FileName1 and
2
331 Dim iFile As Integer
' 1 or
2
332 Const cstPyHelper =
"$
" & "_SF_FileSystem__CompareFiles
"
334 Const cstThisSub =
"FileSystem.CompareFiles
"
335 Const cstSubArgs =
"FileName1, FileName2, [CompareContents=False]
"
337 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
341 If IsMissing(CompareContents) Or IsEmpty(CompareContents) Then CompareContents = False
342 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
343 If Not SF_Utils._ValidateFile(FileName1,
"FileName1
", False) Then GoTo Finally
344 If Not SF_Utils._ValidateFile(FileName2,
"FileName2
", False) Then GoTo Finally
345 If Not SF_Utils._Validate(CompareContents,
"CompareContents
", V_BOOLEAN) Then GoTo Finally
347 ' Do the files exist ? Otherwise raise error
348 sFile = FileName1 : iFile =
1
349 If Not SF_FileSystem.FileExists(sFile) Then GoTo CatchNotExists
350 sFile = FileName2 : iFile =
2
351 If Not SF_FileSystem.FileExists(sFile) Then GoTo CatchNotExists
353 sFile = FileName1 : iFile =
1
354 If SF_FileSystem._IsDocFileSystem(sFile) Then GoTo CatchNotSupported
355 sFile = FileName2 : iFile =
2
356 If SF_FileSystem._IsDocFileSystem(sFile) Then GoTo CatchNotSupported
359 With ScriptForge.SF_Session
360 bCompare = .ExecutePythonScript(.SCRIPTISSHARED, _SF_.PythonHelper
& cstPyHelper _
361 , _ConvertFromUrl(FileName1) _
362 , _ConvertFromUrl(FileName2) _
367 CompareFiles = bCompare
368 SF_Utils._ExitFunction(cstThisSub)
373 SF_Exception.RaiseFatal(UNKNOWNFILEERROR,
"FileName
" & iFile, sFile)
376 SF_Exception.RaiseFatal(FILESYSTEMERROR,
"FileName
" & iFile, Split(cstThisSub,
".
")(
1), sFile)
378 End Function
' ScriptForge.SF_FileSystem.CompareFiles
380 REM -----------------------------------------------------------------------------
381 Public Function CopyFile(Optional ByVal Source As Variant _
382 , Optional ByVal Destination As Variant _
383 , Optional ByVal Overwrite As Variant _
385 ''' Copies one or more files from one location to another
386 ''' Args:
387 ''' Source: FileName or NamePattern which can include wildcard characters, for one or more files to be copied
388 ''' Destination: FileName where the single Source file is to be copied
389 ''' or FolderName where the multiple files from Source are to be copied
390 ''' If FolderName does not exist, it is created
391 ''' Anyway, wildcard characters are not allowed in Destination
392 ''' Overwrite: If True (default), files may be overwritten
393 ''' CopyFile will fail if Destination has the read-only attribute set, regardless of the value of Overwrite.
394 ''' Returns:
395 ''' True if at least one file has been copied
396 ''' False if an error occurred
397 ''' An error also occurs if a source using wildcard characters doesn
't match any files.
398 ''' The method stops on the first error it encounters
399 ''' No attempt is made to roll back or undo any changes made before an error occurs
400 ''' Exceptions:
401 ''' UNKNOWNFILEERROR Source does not exist
402 ''' UNKNOWNFOLDERERROR Source folder or Destination folder does not exist
403 ''' NOFILEMATCHERROR No file matches Source containing wildcards
404 ''' NOTAFOLDERERROR Destination is a file, not a folder
405 ''' NOTAFILEERROR Destination is a folder, not a file
406 ''' OVERWRITEERROR Destination can not be overwritten
407 ''' READONLYERROR Destination has its read-only attribute set
408 ''' Example:
409 ''' FSO.FileNaming =
"SYS
"
410 ''' FSO.CopyFile(
"C:\Windows\*.*
",
"C:\Temp\
", Overwrite := False)
' Only files are copied, subfolders are not
412 Dim bCopy As Boolean
' Return value
414 Const cstThisSub =
"FileSystem.CopyFile
"
415 Const cstSubArgs =
"Source, Destination, [Overwrite=True]
"
417 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
421 If IsMissing(Overwrite) Or IsEmpty(Overwrite) Then Overwrite = True
422 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
423 If Not SF_Utils._ValidateFile(Source,
"Source
", True) Then GoTo Finally
424 If Not SF_Utils._ValidateFile(Destination,
"Destination
", False) Then GoTo Finally
425 If Not SF_Utils._Validate(Overwrite,
"Overwrite
", V_BOOLEAN) Then GoTo Finally
429 bCopy = SF_FileSystem._CopyMove(
"CopyFile
", Source, Destination, Overwrite)
433 SF_Utils._ExitFunction(cstThisSub)
437 End Function
' ScriptForge.SF_FileSystem.CopyFile
439 REM -----------------------------------------------------------------------------
440 Public Function CopyFolder(Optional ByVal Source As Variant _
441 , Optional ByVal Destination As Variant _
442 , Optional ByVal Overwrite As Variant _
444 ''' Copies one or more folders from one location to another
445 ''' Args:
446 ''' Source: FolderName or NamePattern which can include wildcard characters, for one or more folders to be copied
447 ''' Destination: FolderName where the single Source folder is to be copied
448 ''' or FolderName where the multiple folders from Source are to be copied
449 ''' If FolderName does not exist, it is created
450 ''' Anyway, wildcard characters are not allowed in Destination
451 ''' Overwrite: If True (default), folders and their content may be overwritten
452 ''' CopyFile will fail if Destination has the read-only attribute set, regardless of the value of Overwrite.
453 ''' Returns:
454 ''' True if at least one folder has been copied
455 ''' False if an error occurred
456 ''' An error also occurs if a source using wildcard characters doesn
't match any folders.
457 ''' The method stops on the first error it encounters
458 ''' No attempt is made to roll back or undo any changes made before an error occurs
459 ''' Exceptions:
460 ''' UNKNOWNFILEERROR Source does not exist
461 ''' UNKNOWNFOLDERERROR Source folder or Destination folder does not exist
462 ''' NOFILEMATCHERROR No file matches Source containing wildcards
463 ''' NOTAFOLDERERROR Destination is a file, not a folder
464 ''' OVERWRITEERROR Destination can not be overwritten
465 ''' READONLYERROR Destination has its read-only attribute set
466 ''' Example:
467 ''' FSO.FileNaming =
"SYS
"
468 ''' FSO.CopyFolder(
"C:\Windows\*
",
"C:\Temp\
", Overwrite := False)
470 Dim bCopy As Boolean
' Return value
472 Const cstThisSub =
"FileSystem.CopyFolder
"
473 Const cstSubArgs =
"Source, Destination, [Overwrite=True]
"
475 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
479 If IsMissing(Overwrite) Or IsEmpty(Overwrite) Then Overwrite = True
480 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
481 If Not SF_Utils._ValidateFile(Source,
"Source
", True) Then GoTo Finally
482 If Not SF_Utils._ValidateFile(Destination,
"Destination
", False) Then GoTo Finally
483 If Not SF_Utils._Validate(Overwrite,
"Overwrite
", V_BOOLEAN) Then GoTo Finally
487 bCopy = SF_FileSystem._CopyMove(
"CopyFolder
", Source, Destination, Overwrite)
491 SF_Utils._ExitFunction(cstThisSub)
495 End Function
' ScriptForge.SF_FileSystem.CopyFolder
497 REM -----------------------------------------------------------------------------
498 Public Function CreateFolder(Optional ByVal FolderName As Variant) As Boolean
499 ''' Return True if the given folder name could be created successfully
500 ''' The parent folder does not need to exist beforehand
501 ''' Args:
502 ''' FolderName: a string representing the folder to create. It must not exist
503 ''' Returns:
504 ''' True if FolderName is a valid folder name, does not exist and creation was successful
505 ''' False otherwise including when FolderName is a file
506 ''' Exceptions:
507 ''' FOLDERCREATIONERROR FolderName is an existing folder or file
508 ''' Example:
509 ''' FSO.FileNaming =
"SYS
"
510 ''' FSO.CreateFolder(
"C:\NewFolder\
")
512 Dim bCreate As Boolean
' Return value
513 Dim oSfa As Object
' com.sun.star.ucb.SimpleFileAccess
515 Const cstThisSub =
"FileSystem.CreateFolder
"
516 Const cstSubArgs =
"FolderName
"
518 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
522 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
523 If Not SF_Utils._ValidateFile(FolderName,
"FolderName
") Then GoTo Finally
527 Set oSfa = SF_Utils._GetUnoService(
"FileAccess
")
528 If SF_FileSystem.FolderExists(FolderName) Then GoTo CatchExists
529 If SF_FileSystem.FileExists(FolderName) Then GoTo CatchExists
530 oSfa.createFolder(SF_FileSystem._ConvertToUrl(FolderName))
534 CreateFolder = bCreate
535 SF_Utils._ExitFunction(cstThisSub)
540 SF_Exception.RaiseFatal(FOLDERCREATIONERROR,
"FolderName
", FolderName)
542 End Function
' ScriptForge.SF_FileSystem.CreateFolder
544 REM -----------------------------------------------------------------------------
545 Public Function CreateTextFile(Optional ByVal FileName As Variant _
546 , Optional ByVal Overwrite As Variant _
547 , Optional ByVal Encoding As Variant _
549 ''' Creates a specified file and returns a TextStream object that can be used to write to the file
550 ''' Args:
551 ''' FileName: Identifies the file to create
552 ''' Overwrite: Boolean value that indicates if an existing file can be overwritten (default = True)
553 ''' Encoding: The character set that should be used
554 ''' Use one of the Names listed in https://www.iana.org/assignments/character-sets/character-sets.xhtml
555 ''' Note that LibreOffice does not implement all existing sets
556 ''' Default = UTF-
8
557 ''' Returns:
558 ''' An instance of the SF_TextStream class representing the opened file or a Null object if an error occurred
559 ''' It doesn
't check either if the given encoding is implemented in LibreOffice
560 ''' Exceptions:
561 ''' OVERWRITEERROR File exists, creation impossible
562 ''' Example:
563 ''' Dim myFile As Object
564 ''' FSO.FileNaming =
"SYS
"
565 ''' Set myFile = FSO.CreateTextFile(
"C:\Temp\ThisFile.txt
", Overwrite := True)
567 Dim oTextStream As Object
' Return value
568 Const cstThisSub =
"FileSystem.CreateTextFile
"
569 Const cstSubArgs =
"FileName, [Overwrite=True], [Encoding=
""UTF-
8""]
"
571 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
572 Set oTextStream = Nothing
575 If IsMissing(Overwrite) Or IsEmpty(Overwrite) Then Overwrite = True
576 If IsMissing(Encoding) Or IsEmpty(Encoding) Then Encoding =
"UTF-
8"
577 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
578 If Not SF_Utils._ValidateFile(FileName,
"FileName
") Then GoTo Finally
579 If Not SF_Utils._Validate(Overwrite,
"Overwrite
", V_BOOLEAN) Then GoTo Finally
580 If Not SF_Utils._Validate(Encoding,
"Encoding
", V_STRING) Then GoTo Finally
584 If .FileExists(FileName) Then
585 If Overwrite Then .DeleteFile(FileName) Else GoTo CatchOverWrite
589 Set oTextStream = .OpenTextFile(FileName, .ForWriting, Create := True, Encoding := Encoding)
593 Set CreateTextFile = oTextStream
594 SF_Utils._ExitFunction(cstThisSub)
599 SF_Exception.RaiseFatal(OVERWRITEERROR,
"FileName
", FileName)
601 End Function
' ScriptForge.SF_FileSystem.CreateTextFile
603 REM -----------------------------------------------------------------------------
604 Public Function DeleteFile(Optional ByVal FileName As Variant) As Boolean
605 ''' Deletes one or more files
606 ''' Args:
607 ''' FileName: FileName or NamePattern which can include wildcard characters, for one or more files to be deleted
608 ''' Returns:
609 ''' True if at least one file has been deleted
610 ''' False if an error occurred
611 ''' An error also occurs if a FileName using wildcard characters doesn
't match any files.
612 ''' The method stops on the first error it encounters
613 ''' No attempt is made to roll back or undo any changes made before an error occurs
614 ''' Exceptions:
615 ''' UNKNOWNFILEERROR FileName does not exist
616 ''' NOFILEMATCHERROR No file matches FileName containing wildcards
617 ''' NOTAFILEERROR Argument is a folder, not a file
618 ''' Example:
619 ''' FSO.FileNaming =
"SYS
"
620 ''' FSO.DeleteFile(
"C:\Temp\*.*
")
' Only files are deleted, subfolders are not
622 Dim bDelete As Boolean
' Return value
624 Const cstThisSub =
"FileSystem.DeleteFile
"
625 Const cstSubArgs =
"FileName
"
627 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
631 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
632 If Not SF_Utils._ValidateFile(FileName,
"FileName
", True) Then GoTo Finally
636 bDelete = SF_FileSystem._Delete(
"DeleteFile
", FileName)
640 SF_Utils._ExitFunction(cstThisSub)
644 End Function
' ScriptForge.SF_FileSystem.DeleteFile
646 REM -----------------------------------------------------------------------------
647 Public Function DeleteFolder(Optional ByVal FolderName As Variant) As Boolean
648 ''' Deletes one or more Folders
649 ''' Args:
650 ''' FolderName: FolderName or NamePattern which can include wildcard characters, for one or more Folders to be deleted
651 ''' Returns:
652 ''' True if at least one folder has been deleted
653 ''' False if an error occurred
654 ''' An error also occurs if a FolderName using wildcard characters doesn
't match any folders.
655 ''' The method stops on the first error it encounters
656 ''' No attempt is made to roll back or undo any changes made before an error occurs
657 ''' Exceptions:
658 ''' UNKNOWNFOLDERERROR FolderName does not exist
659 ''' NOFILEMATCHERROR No folder matches FolderName containing wildcards
660 ''' NOTAFOLDERERROR Argument is a file, not a folder
661 ''' Example:
662 ''' FSO.FileNaming =
"SYS
"
663 ''' FSO.DeleteFolder(
"C:\Temp\*
")
' Only folders are deleted, files in the parent folder are not
665 Dim bDelete As Boolean
' Return value
667 Const cstThisSub =
"FileSystem.DeleteFolder
"
668 Const cstSubArgs =
"FolderName
"
670 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
674 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
675 If Not SF_Utils._ValidateFile(FolderName,
"FolderName
", True) Then GoTo Finally
679 bDelete = SF_FileSystem._Delete(
"DeleteFolder
", FolderName)
682 DeleteFolder = bDelete
683 SF_Utils._ExitFunction(cstThisSub)
687 End Function
' ScriptForge.SF_FileSystem.DeleteFolder
689 REM -----------------------------------------------------------------------------
690 Public Function ExtensionFolder(Optional ByVal Extension As Variant) As String
691 ''' Return the folder where the given extension is installed. The argument must
692 ''' be in the list of extensions provided by the SF_Platform.Extensions property
693 ''' Args:
694 ''' Extension: a valid extension name
695 ''' Returns:
696 ''' The requested folder using the FileNaming notation
697 ''' Example:
698 ''' MsgBox FSO.ExtensionFolder(
"apso.python.script.organizer
")
700 Dim sFolder As String
' Return value
701 Static vExtensions As Variant
' Cached list of existing extension names
702 Dim oPackage As Object
' /singletons/com.sun.star.deployment.PackageInformationProvider
703 Const cstThisSub =
"FileSystem.ExtensionFolder
"
704 Const cstSubArgs =
"Extension
"
706 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
707 sFolder =
""
710 If IsEmpty(vExtensions) Then vExtensions = SF_Platform.Extensions
711 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
712 If Not SF_Utils._Validate(Extension,
"Extension
", V_STRING, vExtensions, True) Then GoTo Finally
716 ' Search an individual folder
717 Set oPackage = SF_Utils._GetUnoService(
"PackageInformationProvider
")
718 sFolder = oPackage.getPackageLocation(Extension)
721 ExtensionFolder = SF_FileSystem._ConvertFromUrl(sFolder)
722 SF_Utils._ExitFunction(cstThisSub)
726 End Function
' ScriptForge.SF_FileSystem.ExtensionFolder
728 REM -----------------------------------------------------------------------------
729 Public Function FileExists(Optional ByVal FileName As Variant) As Boolean
730 ''' Return True if the given file exists
731 ''' Args:
732 ''' FileName: a string representing a file
733 ''' Returns:
734 ''' True if FileName is a valid File name and it exists
735 ''' False otherwise including when FileName is a folder
736 ''' Example:
737 ''' FSO.FileNaming =
"SYS
"
738 ''' If FSO.FileExists(
"C:\Notepad.exe
") Then ...
740 Dim bExists As Boolean
' Return value
741 Dim oSfa As Object
' com.sun.star.ucb.SimpleFileAccess
743 Const cstThisSub =
"FileSystem.FileExists
"
744 Const cstSubArgs =
"FileName
"
746 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
750 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
751 If Not SF_Utils._ValidateFile(FileName,
"FileName
") Then GoTo Finally
753 FileName = SF_FileSystem._ConvertToUrl(FileName)
756 Set oSfa = SF_Utils._GetUnoService(
"FileAccess
")
757 bExists = oSfa.exists(FileName) And Not oSfa.isFolder(FileName)
761 SF_Utils._ExitFunction(cstThisSub)
765 End Function
' ScriptForge.SF_FileSystem.FileExists
767 REM -----------------------------------------------------------------------------
768 Public Function Files(Optional ByVal FolderName As Variant _
769 , Optional ByVal Filter As Variant _
770 , Optional ByVal IncludeSubfolders As Variant _
772 ''' Return an array of the FileNames stored in the given folder. The folder must exist
773 ''' Subfolders may be optionally explored too.
774 ''' If the number of files exceeds a reasonable amount (
> 1000 ?), the process time may become long.
775 ''' Args:
776 ''' FolderName: the folder to explore
777 ''' Filter: contains wildcards (
"?
" and
"*
") to limit the list to the relevant files (default =
"")
778 ''' IncludeSubfolders: when True (default = False), subfolders are explored too.
779 ''' Returns:
780 ''' An array of strings, each entry is the FileName of an existing file
781 ''' Exceptions:
782 ''' UNKNOWNFOLDERERROR Folder does not exist
783 ''' NOTAFOLDERERROR FolderName is a file, not a folder
784 ''' Example:
785 ''' Dim a As Variant
786 ''' FSO.FileNaming =
"SYS
"
787 ''' a = FSO.Files(
"C:\Windows\
", IncludeSubfolders := True)
789 Dim vFiles As Variant
' Return value
790 Dim oSfa As Object
' com.sun.star.ucb.SimpleFileAccess
791 Dim sFilesColl As String
' cstSEPARATOR delimited string of list of files (FileNaming notation)
794 Const cstThisSub =
"FileSystem.Files
"
795 Const cstSubArgs =
"FolderName, [Filter=
""""], [IncludeSubfolders=False]
"
797 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
801 If IsMissing(Filter) Or IsEmpty(Filter) Then Filter =
""
802 If IsMissing(IncludeSubfolders) Or IsEmpty(IncludeSubfolders) Then IncludeSubfolders = False
803 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
804 If Not SF_Utils._ValidateFile(FolderName,
"FolderName
") Then GoTo Finally
805 If Not SF_Utils._Validate(Filter,
"Filter
", V_STRING) Then GoTo Finally
806 If Not SF_Utils._Validate(IncludeSubfolders,
"IncludeSubfolders
", V_BOOLEAN) Then GoTo Finally
808 If SF_FileSystem.FileExists(FolderName) Then GoTo CatchFile
' Must not be a file
809 If Not SF_FileSystem.FolderExists(FolderName) Then GoTo CatchFolder
' Folder must exist
812 sFilesColl =
""
813 Set oSfa = SF_Utils._GetUnoService(
"FileAccess
")
814 SF_FileSystem._ScanFolder(cstFiles, sFilesColl, FolderName, oSfa, Filter, IncludeSubfolders)
816 If Len(sFilesColl)
> Len(cstSEPARATOR) Then vFiles() = Split(Mid(sFilesColl, Len(cstSEPARATOR) +
1), cstSEPARATOR)
820 SF_Utils._ExitFunction(cstThisSub)
825 SF_Exception.RaiseFatal(NOTAFOLDERERROR,
"FolderName
", FolderName)
828 SF_Exception.RaiseFatal(UNKNOWNFOLDERERROR,
"FolderName
", FolderName)
830 End Function
' ScriptForge.SF_FileSystem.Files
832 REM -----------------------------------------------------------------------------
833 Public Function FolderExists(Optional ByVal FolderName As Variant) As Boolean
834 ''' Return True if the given folder name exists
835 ''' Args:
836 ''' FolderName: a string representing a folder
837 ''' Returns:
838 ''' True if FolderName is a valid folder name and it exists
839 ''' False otherwise including when FolderName is a file
840 ''' Example:
841 ''' FSO.FileNaming =
"SYS
"
842 ''' If FSO.FolderExists(
"C:\
") Then ...
844 Dim bExists As Boolean
' Return value
845 Dim oSfa As Object
' com.sun.star.ucb.SimpleFileAccess
847 Const cstThisSub =
"FileSystem.FolderExists
"
848 Const cstSubArgs =
"FolderName
"
850 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
854 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
855 If Not SF_Utils._ValidateFile(FolderName,
"FolderName
") Then GoTo Finally
857 FolderName = SF_FileSystem._ConvertToUrl(FolderName)
860 Set oSfa = SF_Utils._GetUnoService(
"FileAccess
")
861 bExists = oSfa.isFolder(FolderName)
864 FolderExists = bExists
865 SF_Utils._ExitFunction(cstThisSub)
869 End Function
' ScriptForge.SF_FileSystem.FolderExists
871 REM -----------------------------------------------------------------------------
872 Public Function GetBaseName(Optional ByVal FileName As Variant) As String
873 ''' Returns the BaseName part of the last component of a File- or FolderName, without its extension
874 ''' The method does not check for the existence of the specified file or folder
875 ''' Args:
876 ''' FileName: Path and file name
877 ''' Returns:
878 ''' The BaseName of the given argument in native operating system format. May be empty
879 ''' Example:
880 ''' Dim a As String
881 ''' FSO.FileNaming =
"SYS
"
882 ''' a = FSO.GetBaseName(
"C:\Windows\Notepad.exe
") returns Notepad
884 Dim sBase As String
' Return value
885 Dim sExt As String
' Extension
886 Dim sName As String
' Last component of FileName
887 Dim vName As Variant
' Array of trunks of sName
888 Const cstThisSub =
"FileSystem.GetBaseName
"
889 Const cstSubArgs =
"FileName
"
891 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
895 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
896 If Not SF_Utils._ValidateFile(FileName,
"FileName
") Then GoTo Finally
900 sName = SF_FileSystem.GetName(FileName)
901 If Len(sName)
> 0 Then
902 If InStr(sName,
".
")
> 0 Then
903 vName = Split(sName,
".
")
904 sExt = vName(UBound(vName))
905 sBase = Left(sName, Len(sName) - Len(sExt) -
1)
913 SF_Utils._ExitFunction(cstThisSub)
917 End Function
' ScriptForge.SF_FileSystem.GetBaseName
919 REM -----------------------------------------------------------------------------
920 Public Function GetExtension(Optional ByVal FileName As Variant) As String
921 ''' Returns the extension part of a File- or FolderName, without the dot (.).
922 ''' The method does not check for the existence of the specified file or folder
923 ''' Args:
924 ''' FileName: Path and file name
925 ''' Returns:
926 ''' The extension without a leading dot. May be empty
927 ''' Example:
928 ''' Dim a As String
929 ''' FSO.FileNaming =
"SYS
"
930 ''' a = FSO.GetExtension(
"C:\Windows\Notepad.exe
") returns exe
932 Dim sExt As String
' Return value
933 Dim sName As String
' Last component of FileName
934 Dim vName As Variant
' Array of trunks of sName
935 Const cstThisSub =
"FileSystem.GetExtension
"
936 Const cstSubArgs =
"FileName
"
938 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
942 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
943 If Not SF_Utils._ValidateFile(FileName,
"FileName
") Then GoTo Finally
947 sName = SF_FileSystem.GetName(FileName)
948 If Len(sName)
> 0 And InStr(sName,
".
")
> 0 Then
949 vName = Split(sName,
".
")
950 sExt = vName(UBound(vName))
955 SF_Utils._ExitFunction(cstThisSub)
959 End Function
' ScriptForge.SF_FileSystem.GetExtension
961 REM -----------------------------------------------------------------------------
962 Public Function GetFileLen(Optional ByVal FileName As Variant) As Currency
963 ''' Return file size in bytes with four decimals
'''
964 ''' Args:
965 ''' FileName: a string representing a file
966 ''' Returns:
967 ''' File size if FileName exists
968 ''' 0 when FileName belongs to a document
's internal file systems.
969 ''' Exceptions:
970 ''' UNKNOWNFILEERROR The file does not exist or is a folder
971 ''' Example:
972 ''' Print SF_FileSystem.GetFileLen(
"C:\pagefile.sys
")
974 Dim curSize As Currency
' Return value
975 Const cstPyHelper =
"$
" & "_SF_FileSystem__GetFilelen
"
976 Const cstThisSub =
"FileSystem.GetFileLen
"
977 Const cstSubArgs =
"FileName
"
979 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
983 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
984 If Not SF_Utils._ValidateFile(FileName,
"FileName
") Then GoTo Finally
988 If SF_FileSystem.FileExists(FileName) Then
989 If SF_FileSystem._IsDocFileSystem(FileName) Then
992 With ScriptForge.SF_Session
993 curSize = .ExecutePythonScript(.SCRIPTISSHARED, _SF_.PythonHelper
& cstPyHelper _
994 , _ConvertFromUrl(FileName))
1002 GetFileLen = curSize
1003 SF_Utils._ExitFunction(cstThisSub)
1008 SF_Exception.RaiseFatal(UNKNOWNFILEERROR,
"FileName
", FileName)
1010 End Function
' ScriptForge.SF_FileSystem.GetFileLen
1012 REM -----------------------------------------------------------------------------
1013 Public Function GetFileModified(Optional ByVal FileName As Variant) As Variant
1014 ''' Returns the last modified date for the given file
1015 ''' The method is not supported for document
's internal file systems.
1016 ''' Args:
1017 ''' FileName: a string representing an existing file
1018 ''' Returns:
1019 ''' The modification date and time as a Basic Date
1020 ''' Exceptions:
1021 ''' UNKNOWNFILEERROR The file does not exist or is a folder
1022 ''' FILESYSTEMERROR The method is not applicable on document
's file systems
1023 ''' Example:
1024 ''' Dim a As Date
1025 ''' FSO.FileNaming =
"SYS
"
1026 ''' a = FSO.GetFileModified(
"C:\Temp\myDoc.odt
")
1028 Dim dModified As Date
' Return value
1029 Dim oModified As New com.sun.star.util.DateTime
1030 Dim oSfa As Object
' com.sun.star.ucb.SimpleFileAccess
1032 Const cstThisSub =
"FileSystem.GetFileModified
"
1033 Const cstSubArgs =
"FileName
"
1035 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1039 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1040 If Not SF_Utils._ValidateFile(FileName,
"FileName
") Then GoTo Finally
1042 If SF_FileSystem._IsDocFileSystem(FileName) Then GoTo CatchNotSupported
1045 Set oSfa = SF_Utils._GetUnoService(
"FileAccess
")
1046 If SF_FileSystem.FileExists(FileName) Then
1047 FileName = SF_FileSystem._ConvertToUrl(FileName)
1048 Set oModified = oSfa.getDateTimeModified(FileName)
1049 dModified = CDateFromUnoDateTime(oModified)
1055 GetFileModified = dModified
1056 SF_Utils._ExitFunction(cstThisSub)
1061 SF_Exception.RaiseFatal(UNKNOWNFILEERROR,
"FileName
", FileName)
1064 SF_Exception.RaiseFatal(FILESYSTEMERROR,
"FileName
", Split(cstThisSub,
".
")(
1), FileName)
1066 End Function
' ScriptForge.SF_FileSystem.GetFileModified
1068 REM -----------------------------------------------------------------------------
1069 Public Function GetName(Optional ByVal FileName As Variant) As String
1070 ''' Returns the last component of a File- or FolderName
1071 ''' The method does not check for the existence of the specified file or folder
1072 ''' Args:
1073 ''' FileName: Path and file name
1074 ''' Returns:
1075 ''' The last component of the full file name in native operating system format
1076 ''' Example:
1077 ''' Dim a As String
1078 ''' FSO.FileNaming =
"SYS
"
1079 ''' a = FSO.GetName(
"C:\Windows\Notepad.exe
") returns Notepad.exe
1081 Dim sName As String
' Return value
1082 Dim vFile As Variant
' Array of components
1083 Const cstThisSub =
"FileSystem.GetName
"
1084 Const cstSubArgs =
"FileName
"
1086 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1087 sName =
""
1090 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1091 If Not SF_Utils._ValidateFile(FileName,
"FileName
") Then GoTo Finally
1093 FileName = SF_FileSystem._ConvertToUrl(FileName)
1096 If Len(FileName)
> 0 Then
1097 If Right(FileName,
1) =
"/
" Then FileName = Left(FileName, Len(FileName) -
1)
1098 vFile = Split(FileName,
"/
")
1099 sName = ConvertFromUrl(vFile(UBound(vFile)))
' Always in SYS format
1104 SF_Utils._ExitFunction(cstThisSub)
1108 End Function
' ScriptForge.SF_FileSystem.GetName
1110 REM -----------------------------------------------------------------------------
1111 Public Function GetParentFolderName(Optional ByVal FileName As Variant) As String
1112 ''' Returns a string containing the name of the parent folder of the last component in a specified File- or FolderName
1113 ''' The method does not check for the existence of the specified file or folder
1114 ''' Args:
1115 ''' FileName: Path and file name
1116 ''' Returns:
1117 ''' A FolderName including its final path separator
1118 ''' Example:
1119 ''' Dim a As String
1120 ''' FSO.FileNaming =
"SYS
"
1121 ''' a = FSO.GetParentFolderName(
"C:\Windows\Notepad.exe
") returns C:\Windows\
1123 Dim sFolder As String
' Return value
1124 Dim sName As String
' Last component of FileName
1125 Dim vFile As Variant
' Array of file components
1126 Const cstThisSub =
"FileSystem.GetParentFolderName
"
1127 Const cstSubArgs =
"FileName
"
1129 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1130 sFolder =
""
1133 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1134 If Not SF_Utils._ValidateFile(FileName,
"FileName
") Then GoTo Finally
1136 FileName = SF_FileSystem._ConvertToUrl(FileName)
1139 If Right(FileName,
1) =
"/
" Then FileName = Left(FileName, Len(FileName) -
1)
1140 vFile = Split(FileName,
"/
")
1141 If UBound(vFile)
>=
0 Then vFile(UBound(vFile)) =
""
1142 sFolder = Join(vFile,
"/
")
1143 If sFolder =
"" Or Right(sFolder,
1)
<> "/
" Then sFolder = sFolder
& "/
"
1146 GetParentFolderName = SF_FileSystem._ConvertFromUrl(sFolder)
1147 SF_Utils._ExitFunction(cstThisSub)
1151 End Function
' ScriptForge.SF_FileSystem.GetParentFolderName
1153 REM -----------------------------------------------------------------------------
1154 Public Function GetProperty(Optional ByVal PropertyName As Variant) As Variant
1155 ''' Return the actual value of the given property
1156 ''' Args:
1157 ''' PropertyName: the name of the property as a string
1158 ''' Returns:
1159 ''' The actual value of the property
1160 ''' Exceptions
1161 ''' ARGUMENTERROR The property does not exist
1163 Const cstThisSub =
"FileSystem.GetProperty
"
1164 Const cstSubArgs =
"PropertyName
"
1166 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1170 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1171 If Not SF_Utils._Validate(PropertyName,
"PropertyName
", V_STRING, Properties()) Then GoTo Catch
1175 Select Case UCase(PropertyName)
1176 Case UCase(
"ConfigFolder
") : GetProperty = ConfigFolder
1177 Case UCase(
"ExtensionsFolder
") : GetProperty = ExtensionsFolder
1178 Case UCase(
"FileNaming
") : GetProperty = FileNaming
1179 Case UCase(
"HomeFolder
") : GetProperty = HomeFolder
1180 Case UCase(
"InstallFolder
") : GetProperty = InstallFolder
1181 Case UCase(
"TemplatesFolder
") : GetProperty = TemplatesFolder
1182 Case UCase(
"TemporaryFolder
") : GetProperty = TemporaryFolder
1183 Case UCase(
"UserTemplatesFolder
") : GetProperty = UserTemplatesFolder
1188 SF_Utils._ExitFunction(cstThisSub)
1192 End Function
' ScriptForge.SF_FileSystem.GetProperty
1194 REM -----------------------------------------------------------------------------
1195 Public Function GetTempName(Optional ByVal Extension As Variant) As String
1196 ''' Returns a randomly generated temporary file name that is useful for performing
1197 ''' operations that require a temporary file : the method does not create any file
1198 ''' Args:
1199 ''' Returns:
1200 ''' A FileName as a String that can be used f.i. with CreateTextFile()
1201 ''' The FileName has as suffix the given extension.
1202 ''' Example:
1203 ''' Dim a As String
1204 ''' FSO.FileNaming =
"SYS
"
1205 ''' a = FSO.GetTempName(
"txt
")
' /tmp/SF_123456.txt
1206 ''' a = FSO.GetTempName()
' /tmp/SF_234567
1208 Dim sFile As String
' Return value
1209 Dim sExtension As String
' The given extension preceded by a dot
1210 Dim lRandom As Long
' Random integer
1212 Const cstThisSub =
"FileSystem.GetTempName
"
1213 Const cstSubArgs =
""
1215 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1216 sFile =
""
1219 If IsMissing(Extension) Or IsEmpty(Extension) Then Extension =
""
1220 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1221 If Not SF_Utils._Validate(Extension,
"Extension
", V_STRING) Then GoTo Catch
1225 lRandom = SF_Session.ExecuteCalcFunction(
"RANDBETWEEN.NV
",
1,
999999)
1226 If Len(Extension)
> 0 Then sExtension =
".
" & Extension Else sExtension =
""
1227 sFile = SF_FileSystem.TemporaryFolder
& "SF_
" & Right(
"000000" & lRandom,
6)
& sExtension
1230 GetTempName = SF_FileSystem._ConvertFromUrl(sFile)
1231 SF_Utils._ExitFunction(cstThisSub)
1235 End Function
' ScriptForge.SF_FileSystem.GetTempName
1237 REM -----------------------------------------------------------------------------
1238 Public Function HashFile(Optional ByVal FileName As Variant _
1239 , Optional ByVal Algorithm As Variant _
1241 ''' Return an hexadecimal string representing a checksum of the given file
1242 ''' Next algorithms are supported: MD5, SHA1, SHA224, SHA256, SHA384 and SHA512
1243 ''' The method is not supported for document
's internal file systems.
1244 ''' Args:
1245 ''' FileName: a string representing a file
1246 ''' Algorithm: The hashing algorithm to use
1247 ''' Returns:
1248 ''' The requested checksum as a string. Hexadecimal digits are lower-cased
1249 ''' A zero-length string when an error occurred
1250 ''' Exceptions:
1251 ''' UNKNOWNFILEERROR The file does not exist or is a folder
1252 ''' FILESYSTEMERROR The method is not applicable on document
's file systems
1253 ''' Example:
1254 ''' Print SF_FileSystem.HashFile(
"C:\pagefile.sys
",
"MD5
")
1256 Dim sHash As String
' Return value
1257 Const cstPyHelper =
"$
" & "_SF_FileSystem__HashFile
"
1258 Const cstThisSub =
"FileSystem.HashFile
"
1259 Const cstSubArgs =
"FileName, Algorithm=
""MD5
""|
""SHA1
""|
""SHA224
""|
""SHA256
""|
""SHA384
""|
""SHA512
"""
1261 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1262 sHash =
""
1265 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1266 If Not SF_Utils._ValidateFile(FileName,
"FileName
") Then GoTo Finally
1267 If Not SF_Utils._Validate(Algorithm,
"Algorithm
", V_STRING _
1268 , Array(
"MD5
",
"SHA1
",
"SHA224
",
"SHA256
",
"SHA384
",
"SHA512
")) Then GoTo Finally
1270 If SF_FileSystem._IsDocFileSystem(FileName) Then GoTo CatchNotSupported
1273 If SF_FileSystem.FileExists(FileName) Then
1274 With ScriptForge.SF_Session
1275 sHash = .ExecutePythonScript(.SCRIPTISSHARED, _SF_.PythonHelper
& cstPyHelper _
1276 , _ConvertFromUrl(FileName), LCase(Algorithm))
1284 SF_Utils._ExitFunction(cstThisSub)
1289 SF_Exception.RaiseFatal(UNKNOWNFILEERROR,
"FileName
", FileName)
1292 SF_Exception.RaiseFatal(FILESYSTEMERROR,
"FileName
", Split(cstThisSub,
".
")(
1), FileName)
1294 End Function
' ScriptForge.SF_FileSystem.HashFile
1296 REM -----------------------------------------------------------------------------
1297 Public Function Methods() As Variant
1298 ''' Return the list or methods of the FileSystem service as an array
1300 Methods = Array(
"BuildPath
" _
1301 ,
"CompareFiles
" _
1302 ,
"CopyFile
" _
1303 ,
"CopyFolder
" _
1304 ,
"CreateFolder
" _
1305 ,
"CreateTextFile
" _
1306 ,
"DeleteFile
" _
1307 ,
"DeleteFolder
" _
1308 ,
"ExtensionFolder
" _
1309 ,
"FileExists
" _
1310 ,
"Files
" _
1311 ,
"FolderExists
" _
1312 ,
"GetBaseName
" _
1313 ,
"GetExtension
" _
1314 ,
"GetFileLen
" _
1315 ,
"GetFileModified
" _
1316 ,
"GetName
" _
1317 ,
"GetParentFolderName
" _
1318 ,
"GetTempName
" _
1319 ,
"HashFile
" _
1320 ,
"MoveFile
" _
1321 ,
"MoveFolder
" _
1322 ,
"Normalize
" _
1323 ,
"OpenTextFile
" _
1324 ,
"PickFile
" _
1325 ,
"PickFolder
" _
1326 ,
"SubFolders
" _
1329 End Function
' ScriptForge.SF_FileSystem.Methods
1331 REM -----------------------------------------------------------------------------
1332 Public Function MoveFile(Optional ByVal Source As Variant _
1333 , Optional ByVal Destination As Variant _
1335 ''' Moves one or more files from one location to another
1336 ''' Args:
1337 ''' Source: FileName or NamePattern which can include wildcard characters, for one or more files to be moved
1338 ''' Destination: FileName where the single Source file is to be moved
1339 ''' If Source and Destination have the same parent folder MoveFile amounts to renaming the Source
1340 ''' or FolderName where the multiple files from Source are to be moved
1341 ''' If FolderName does not exist, it is created
1342 ''' Anyway, wildcard characters are not allowed in Destination
1343 ''' Returns:
1344 ''' True if at least one file has been moved
1345 ''' False if an error occurred
1346 ''' An error also occurs if a source using wildcard characters doesn
't match any files.
1347 ''' The method stops on the first error it encounters
1348 ''' No attempt is made to roll back or undo any changes made before an error occurs
1349 ''' Exceptions:
1350 ''' UNKNOWNFILEERROR Source does not exist
1351 ''' UNKNOWNFOLDERERROR Source folder or Destination folder does not exist
1352 ''' NOFILEMATCHERROR No file matches Source containing wildcards
1353 ''' NOTAFOLDERERROR Destination is a file, not a folder
1354 ''' NOTAFILEERROR Destination is a folder, not a file
1355 ''' OVERWRITEERROR Destination can not be overwritten
1356 ''' Example:
1357 ''' FSO.FileNaming =
"SYS
"
1358 ''' FSO.MoveFile(
"C:\Temp1\*.*
",
"C:\Temp2\
")
' Only files are moved, subfolders are not
1360 Dim bMove As Boolean
' Return value
1362 Const cstThisSub =
"FileSystem.MoveFile
"
1363 Const cstSubArgs =
"Source, Destination
"
1365 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1369 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1370 If Not SF_Utils._ValidateFile(Source,
"Source
", True) Then GoTo Finally
1371 If Not SF_Utils._ValidateFile(Destination,
"Destination
", False) Then GoTo Finally
1375 bMove = SF_FileSystem._CopyMove(
"MoveFile
", Source, Destination, False)
1379 SF_Utils._ExitFunction(cstThisSub)
1383 End Function
' ScriptForge.SF_FileSystem.MoveFile
1385 REM -----------------------------------------------------------------------------
1386 Public Function MoveFolder(Optional ByVal Source As Variant _
1387 , Optional ByVal Destination As Variant _
1389 ''' Moves one or more folders from one location to another
1390 ''' Args:
1391 ''' Source: FolderName or NamePattern which can include wildcard characters, for one or more folders to be moved
1392 ''' Destination: FolderName where the single Source folder is to be moved
1393 ''' FolderName must not exist
1394 ''' or FolderName where the multiple folders from Source are to be moved
1395 ''' If FolderName does not exist, it is created
1396 ''' Anyway, wildcard characters are not allowed in Destination
1397 ''' Returns:
1398 ''' True if at least one folder has been moved
1399 ''' False if an error occurred
1400 ''' An error also occurs if a source using wildcard characters doesn
't match any folders.
1401 ''' The method stops on the first error it encounters
1402 ''' No attempt is made to roll back or undo any changes made before an error occurs
1403 ''' Exceptions:
1404 ''' UNKNOWNFILEERROR Source does not exist
1405 ''' UNKNOWNFOLDERERROR Source folder or Destination folder does not exist
1406 ''' NOFILEMATCHERROR No file matches Source containing wildcards
1407 ''' NOTAFOLDERERROR Destination is a file, not a folder
1408 ''' OVERWRITEERROR Destination can not be overwritten
1409 ''' Example:
1410 ''' FSO.FileNaming =
"SYS
"
1411 ''' FSO.MoveFolder(
"C:\Temp1\*
",
"C:\Temp2\
")
1413 Dim bMove As Boolean
' Return value
1415 Const cstThisSub =
"FileSystem.MoveFolder
"
1416 Const cstSubArgs =
"Source, Destination
"
1418 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1422 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1423 If Not SF_Utils._ValidateFile(Source,
"Source
", True) Then GoTo Finally
1424 If Not SF_Utils._ValidateFile(Destination,
"Destination
", False) Then GoTo Finally
1428 bMove = SF_FileSystem._CopyMove(
"MoveFolder
", Source, Destination, False)
1432 SF_Utils._ExitFunction(cstThisSub)
1436 End Function
' ScriptForge.SF_FileSystem.MoveFolder
1438 REM -----------------------------------------------------------------------------
1439 Public Function Normalize(Optional ByVal FileName As Variant) As String
1440 ''' Normalize a pathname by collapsing redundant separators and up-level references
1441 ''' so that A//B, A/B/, A/./B and A/foo/../B all become A/B.
1442 ''' On Windows, it converts forward slashes to backward slashes.
1443 ''' The method returns the input string when the file is from a document
's internal file systems.
1444 ''' Args:
1445 ''' FileName: a string representing a file. The file may not exist.
1446 ''' Returns:
1447 ''' The normalized filename in filenaming notation
1448 ''' Example:
1449 ''' Print SF_FileSystem.Normalize(
"A/foo/../B/C/./D//E
")
' A/B/C/D/E
1451 Dim sNorm As String
' Return value
1452 Const cstPyHelper =
"$
" & "_SF_FileSystem__Normalize
"
1453 Const cstThisSub =
"FileSystem.Normalize
"
1454 Const cstSubArgs =
"FileName
"
1456 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1457 sNorm =
""
1460 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1461 If Not SF_Utils._ValidateFile(FileName,
"FileName
") Then GoTo Finally
1465 If SF_FileSystem._IsDocFileSystem(FileName) Then
1468 With ScriptForge.SF_Session
1469 sNorm = .ExecutePythonScript(.SCRIPTISSHARED, _SF_.PythonHelper
& cstPyHelper _
1470 , _ConvertFromUrl(FileName))
1471 ' The Python os.path expects and returns a file name in os notation
1472 If SF_FileSystem.FileNaming
<> "SYS
" Then sNorm = ConvertToUrl(sNorm)
1478 SF_Utils._ExitFunction(cstThisSub)
1482 End Function
' ScriptForge.SF_FileSystem.Normalize
1484 REM -----------------------------------------------------------------------------
1485 Public Function OpenTextFile(Optional ByVal FileName As Variant _
1486 , Optional ByVal IOMode As Variant _
1487 , Optional ByVal Create As Variant _
1488 , Optional ByVal Encoding As Variant _
1490 ''' Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file
1491 ''' Args:
1492 ''' FileName: Identifies the file to open
1493 ''' IOMode: Indicates input/output mode. Can be one of three constants: ForReading, ForWriting, or ForAppending
1494 ''' Create: Boolean value that indicates whether a new file can be created if the specified filename doesn
't exist.
1495 ''' The value is True if a new file and its parent folders may be created; False if they aren
't created (default)
1496 ''' Encoding: The character set that should be used
1497 ''' Use one of the Names listed in https://www.iana.org/assignments/character-sets/character-sets.xhtml
1498 ''' Note that LibreOffice does not implement all existing sets
1499 ''' Default = UTF-
8
1500 ''' Returns:
1501 ''' An instance of the SF_TextStream class representing the opened file or a Null object if an error occurred
1502 ''' The method does not check if the file is really a text file
1503 ''' It doesn
't check either if the given encoding is implemented in LibreOffice nor if it is the right one
1504 ''' Exceptions:
1505 ''' UNKNOWNFILEERROR File does not exist
1506 ''' Example:
1507 ''' Dim myFile As Object
1508 ''' FSO.FileNaming =
"SYS
"
1509 ''' Set myFile = FSO.OpenTextFile(
"C:\Temp\ThisFile.txt
", FSO.ForReading)
1510 ''' If Not IsNull(myFile) Then
' ... Go ahead with reading text lines
1512 Dim oTextStream As Object
' Return value
1513 Dim bExists As Boolean
' When True, file to open does exist
1514 Dim bEmbeddedFile As Boolean
' When True, file to open is embedded in a document
's internal file system
1515 Dim oSfa As Object
' com.sun.star.ucb.SimpleFileAccess
1516 Const cstThisSub =
"FileSystem.OpenTextFile
"
1517 Const cstSubArgs =
"FileName, [IOMode=
1|
2|
8], [Create=False], [Encoding=
""UTF-
8""]
"
1519 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1520 Set oTextStream = Nothing
1524 If IsMissing(IOMode) Or IsEmpty(IOMode) Then IOMode = cstForReading
1525 If IsMissing(Create) Or IsEmpty(Create) Then Create = False
1526 If IsMissing(Encoding) Or IsEmpty(Encoding) Then Encoding =
"UTF-
8"
1527 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1528 If Not SF_Utils._ValidateFile(FileName,
"FileName
") Then GoTo Finally
1529 If Not SF_Utils._Validate(IOMode,
"IOMode
", V_NUMERIC _
1530 , Array(cstForReading, cstForWriting, cstForAppending)) _
1532 If Not SF_Utils._Validate(Create,
"Create
", V_BOOLEAN) Then GoTo Finally
1533 If Not SF_Utils._Validate(Encoding,
"Encoding
", V_STRING) Then GoTo Finally
1536 bExists = .FileExists(FileName)
1538 Case ForReading : If Not bExists Then GoTo CatchNotExists
1539 Case Else : If Not bExists And Not Create Then GoTo CatchNotExists
1542 If IOMode = ForAppending And Not bExists Then IOMode = ForWriting
1544 bEmbeddedFile = SF_FileSystem._IsDocFileSystem(FileName)
1548 ' Create and initialize TextStream class instance
1549 Set oTextStream = New SF_TextStream
1552 .[_Parent] = SF_FileSystem
1553 ._IsEmbeddedFile = bEmbeddedFile
1554 If bEmbeddedFile And (IOMode = cstForWriting Or IOMode = cstForAppending) Then
1555 ' Updates of an embedded file are done on a copy
1556 ._EmbeddedFileName = SF_FileSystem._ConvertToUrl(FileName)
1557 ._FileName = SF_FileSystem._ConvertToUrl(SF_FileSystem.GetTempName(SF_FileSystem.GetExtension(FileName)))
1558 ' Create the copy if relevant
1560 Set oSfa = SF_Utils._GetUnoService(
"FileAccess
")
1561 oSfa.copy(._EmbeddedFileName, ._FileName)
1564 ._FileName = SF_FileSystem._ConvertToUrl(FileName)
1567 ._Encoding = Encoding
1568 ._FileExists = bExists
1573 Set OpenTextFile = oTextStream
1574 SF_Utils._ExitFunction(cstThisSub)
1579 SF_Exception.RaiseFatal(UNKNOWNFILEERROR,
"FileName
", FileName)
1581 End Function
' ScriptForge.SF_FileSystem.OpenTextFile
1583 REM -----------------------------------------------------------------------------
1584 Public Function PickFile(Optional ByVal DefaultFile As Variant _
1585 , Optional ByVal Mode As Variant _
1586 , Optional ByVal Filter As Variant _
1588 ''' Returns the file selected with a FilePicker dialog box
1589 ''' The mode, OPEN or SAVE, and the filter may be preset
1590 ''' If mode = SAVE and the picked file exists, a warning message will be displayed
1591 ''' Modified from Andrew Pitonyak
's Base Macro Programming §
10.4
1592 ''' The method is not supported for document
's internal file systems.
1593 ''' Args:
1594 ''' DefaultFile: Folder part: the FolderName from which to start. Default = the last selected folder
1595 ''' File part: the default file to open or save
1596 ''' Mode:
"OPEN
" (input file) or
"SAVE
" (output file)
1597 ''' Filter: by default only files having the given suffix will be displayed. Default = all suffixes
1598 ''' The filter combo box will contain the given suffix filter (if not
"*
") and
"*.*
"
1599 ''' Returns:
1600 ''' The selected FileName in FileNaming format or
"" if the dialog was cancelled
1601 ''' Exceptions:
1602 ''' FILESYSTEMERROR The method is not applicable on document
's file systems
1603 ''' Example:
1604 ''' FSO.FileNaming =
"SYS
"
1605 ''' FSO.PickFile(
"C:\
",
"OPEN
",
"txt
")
' Only *.txt files are displayed
1607 Dim oFileDialog As Object
' com.sun.star.ui.dialogs.FilePicker
1608 Dim oFileAccess As object
' com.sun.star.ucb.SimpleFileAccess
1609 Dim oPath As Object
' com.sun.star.util.PathSettings
1610 Dim iAccept As Integer
' Result of dialog execution
1611 Dim sInitPath As String
' Current working directory
1612 Dim sBaseFile As String
1613 Dim iMode As Integer
' Numeric alias for SelectMode
1614 Dim sFile As String
' Return value
1616 Const cstThisSub =
"FileSystem.PickFile
"
1617 Const cstSubArgs =
"[DefaultFile=
""""], [Mode=
""OPEN
""|
""SAVE
""],[Filter=
""""]
"
1619 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1620 sFile =
""
1623 If IsMissing(DefaultFile) Or IsEmpty(DefaultFile) Then DefaultFile =
""
1624 If IsMissing(Mode) Or IsEmpty(Mode) Then Mode =
"OPEN
"
1625 If IsMissing(Filter) Or IsEmpty(Filter) Then Filter =
""
1626 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1627 If Not SF_Utils._ValidateFile(DefaultFile,
"DefaultFile
", , True) Then GoTo Finally
1628 If Not SF_Utils._Validate(Mode,
"Mode
", V_STRING, Array(
"OPEN
",
"SAVE
")) Then GoTo Finally
1629 If Not SF_Utils._Validate(Filter,
"Filter
", V_STRING) Then GoTo Finally
1631 If SF_FileSystem._IsDocFileSystem(DefaultFile) Then GoTo CatchNotSupported
1632 DefaultFile = SF_FileSystem._ConvertToUrl(DefaultFile)
1635 ' Derive numeric equivalent of the Mode argument: https://api.libreoffice.org/docs/idl/ref/TemplateDescription_8idl.html
1636 With com.sun.star.ui.dialogs.TemplateDescription
1637 If UCase(Mode) =
"OPEN
" Then iMode = .FILEOPEN_SIMPLE Else iMode = .FILESAVE_AUTOEXTENSION
1640 ' Activate the filepicker dialog
1641 Set oFileDialog = SF_Utils._GetUNOService(
"FilePicker
")
1643 .Initialize(Array(iMode))
1646 If Len(Filter)
> 0 Then .appendFilter(
"*.
" & Filter,
"*.
" & Filter)
' Twice: required by API
1647 .appendFilter(
"*.*
",
"*.*
")
1648 If Len(Filter)
> 0 Then .setCurrentFilter(
"*.
" & Filter) Else .setCurrentFilter(
"*.*
")
1650 ' Set initial folder
1651 If Len(DefaultFile) =
0 Then
' TODO: SF_Session.WorkingFolder
1652 Set oPath = SF_Utils._GetUNOService(
"PathSettings
")
1653 sInitPath = oPath.Work
' Probably My Documents
1655 sInitPath = SF_FileSystem._ParseUrl(ConvertToUrl(DefaultFile)).Path
1658 ' Set default values
1659 Set oFileAccess = SF_Utils._GetUNOService(
"FileAccess
")
1660 If oFileAccess.exists(sInitPath) Then .SetDisplayDirectory(sInitPath)
1661 sBaseFile = SF_FileSystem.GetName(DefaultFile)
1662 .setDefaultName(sBaseFile)
1664 ' Get selected file
1665 iAccept = .Execute()
1666 If iAccept = com.sun.star.ui.dialogs.ExecutableDialogResults.OK Then sFile = .getSelectedFiles()(
0)
1668 ' Do not reuse a FilePicker, side effects observed (a.o. TDF#
154462)
1674 PickFile = SF_FileSystem._ConvertFromUrl(sFile)
1675 SF_Utils._ExitFunction(cstThisSub)
1680 SF_Exception.RaiseFatal(FILESYSTEMERROR,
"DefaultFile
", Split(cstThisSub,
".
")(
1), DefaultFile)
1682 End Function
' ScriptForge.SF_FileSystem.PickFile
1684 REM -----------------------------------------------------------------------------
1685 Public Function PickFolder(Optional ByVal DefaultFolder As Variant _
1686 , Optional ByVal FreeText As Variant _
1688 ''' Display a FolderPicker dialog box
1689 ''' The method is not supported for document
's internal file systems.
1690 ''' Args:
1691 ''' DefaultFolder: the FolderName from which to start. Default = the last selected folder
1692 ''' FreeText: text to display in the dialog. Default =
""
1693 ''' Returns:
1694 ''' The selected FolderName in URL or operating system format
1695 ''' The zero-length string if the dialog was cancelled
1696 ''' Exceptions:
1697 ''' FILESYSTEMERROR The method is not applicable on document
's file systems
1698 ''' Example:
1699 ''' FSO.FileNaming =
"SYS
"
1700 ''' FSO.PickFolder(
"C:\
",
"Choose a folder or press Cancel
")
1702 Dim oFolderDialog As Object
' com.sun.star.ui.dialogs.FolderPicker
1703 Dim iAccept As Integer
' Value returned by the dialog (OK, Cancel, ..)
1704 Dim sFolder As String
' Return value
'
1706 Const cstThisSub =
"FileSystem.PickFolder
"
1707 Const cstSubArgs =
"[DefaultFolder=
""""], [FreeText=
""""]
"
1709 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1710 sFolder =
""
1713 If IsMissing(DefaultFolder) Or IsEmpty(DefaultFolder) Then DefaultFolder =
""
1714 If IsMissing(FreeText) Or IsEmpty(FreeText) Then FreeText =
""
1715 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1716 If Not SF_Utils._ValidateFile(DefaultFolder,
"DefaultFolder
", , True) Then GoTo Finally
1717 If Not SF_Utils._Validate(FreeText,
"FreeText
", V_STRING) Then GoTo Finally
1719 If SF_FileSystem._IsDocFileSystem(DefaultFolder) Then GoTo CatchNotSupported
1720 DefaultFolder = SF_FileSystem._ConvertToUrl(DefaultFolder)
1723 Set oFolderDialog = SF_Utils._GetUNOService(
"FolderPicker
")
1724 If Not IsNull(oFolderDialog) Then
1726 If Len(DefaultFolder)
> 0 Then .DisplayDirectory = ConvertToUrl(DefaultFolder)
1727 .Description = FreeText
1728 iAccept = .Execute()
1729 ' https://api.libreoffice.org/docs/idl/ref/ExecutableDialogResults_8idl.html
1730 If iAccept = com.sun.star.ui.dialogs.ExecutableDialogResults.OK Then
1731 .DisplayDirectory = .Directory
' Set the next default initial folder to the selected one
1732 sFolder = .Directory
& "/
"
1738 PickFolder = SF_FileSystem._ConvertFromUrl(sFolder)
1739 SF_Utils._ExitFunction(cstThisSub)
1744 SF_Exception.RaiseFatal(FILESYSTEMERROR,
"DefaultFolder
", Split(cstThisSub,
".
")(
1), DefaultFolder)
1746 End Function
' ScriptForge.SF_FileSystem.PickFolder
1748 REM -----------------------------------------------------------------------------
1749 Public Function Properties() As Variant
1750 ''' Return the list or properties of the FileSystem module as an array
1752 Properties = Array( _
1753 "ConfigFolder
" _
1754 ,
"ExtensionsFolder
" _
1755 ,
"FileNaming
" _
1756 ,
"HomeFolder
" _
1757 ,
"InstallFolder
" _
1758 ,
"TemplatesFolder
" _
1759 ,
"TemporaryFolder
" _
1760 ,
"UserTemplatesFolder
" _
1763 End Function
' ScriptForge.SF_FileSystem.Properties
1765 REM -----------------------------------------------------------------------------
1766 Public Function SetProperty(Optional ByVal PropertyName As Variant _
1767 , Optional ByRef Value As Variant _
1769 ''' Set a new value to the given property
1770 ''' Args:
1771 ''' PropertyName: the name of the property as a string
1772 ''' Value: its new value
1773 ''' Exceptions
1774 ''' ARGUMENTERROR The property does not exist
1776 Const cstThisSub =
"FileSystem.SetProperty
"
1777 Const cstSubArgs =
"PropertyName, Value
"
1779 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1783 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1784 If Not SF_Utils._Validate(PropertyName,
"PropertyName
", V_STRING, Properties()) Then GoTo Catch
1788 Select Case UCase(PropertyName)
1789 Case UCase(
"FileNaming
") : FileNaming = Value
1794 SF_Utils._ExitFunction(cstThisSub)
1798 End Function
' ScriptForge.SF_FileSystem.SetProperty
1800 REM -----------------------------------------------------------------------------
1801 Public Function SubFolders(Optional ByVal FolderName As Variant _
1802 , Optional ByVal Filter As Variant _
1803 , Optional ByVal IncludeSubfolders As Variant _
1805 ''' Return an array of the FolderNames stored in the given folder. The folder must exist,
1806 ''' Subfolders may be optionally explored too.
1807 ''' Args:
1808 ''' FolderName: the folder to explore
1809 ''' Filter: contains wildcards (
"?
" and
"*
") to limit the list to the relevant folders (default =
"")
1810 ''' IncludeSubfolders: when True (default = False), subfolders are explored too.
1811 ''' Returns:
1812 ''' An array of strings, each entry is the FolderName of an existing folder
1813 ''' Exceptions:
1814 ''' UNKNOWNFOLDERERROR Folder does not exist
1815 ''' NOTAFOLDERERROR FolderName is a file, not a folder
1816 ''' Example:
1817 ''' Dim a As Variant
1818 ''' FSO.FileNaming =
"SYS
"
1819 ''' a = FSO.SubFolders(
"C:\Windows\
", IncludeSubfolders := True)
1821 Dim vSubFolders As Variant
' Return value
1822 Dim oSfa As Object
' com.sun.star.ucb.SimpleFileAccess
1823 Dim sFoldersColl As String
' cstSEPARATOR delimited string of list of folders (FileNaming notation)
1826 Const cstThisSub =
"FileSystem.SubFolders
"
1827 Const cstSubArgs =
"FolderName, [Filter=
""""], [IncludeSubfolders=False]
"
1829 If SF_Utils._ErrorHandling() Then On Local Error GoTo Catch
1830 vSubFolders = Array()
1833 If IsMissing(Filter) Or IsEmpty(Filter) Then Filter =
""
1834 If IsMissing(IncludeSubfolders) Or IsEmpty(IncludeSubfolders) Then IncludeSubfolders = False
1835 If SF_Utils._EnterFunction(cstThisSub, cstSubArgs) Then
1836 If Not SF_Utils._ValidateFile(FolderName,
"FolderName
") Then GoTo Finally
1837 If Not SF_Utils._Validate(Filter,
"Filter
", V_STRING) Then GoTo Finally
1838 If Not SF_Utils._Validate(IncludeSubfolders,
"IncludeSubfolders
", V_BOOLEAN) Then GoTo Finally
1840 If SF_FileSystem.FileExists(FolderName) Then GoTo CatchFile
' Must not be a file
1841 If Not SF_FileSystem.FolderExists(FolderName) Then GoTo CatchFolder
' Top folder must exist
1844 sFoldersColl =
""
1845 Set oSfa = SF_Utils._GetUnoService(
"FileAccess
")
1846 SF_FileSystem._ScanFolder(cstFolders, sFoldersColl, FolderName, oSfa, Filter, IncludeSubfolders)
1848 If Len(sFoldersColl)
> Len(cstSEPARATOR) Then vSubFolders() = Split(Mid(sFoldersColl, Len(cstSEPARATOR) +
1), cstSEPARATOR)
1851 SubFolders = vSubFolders
1852 SF_Utils._ExitFunction(cstThisSub)
1857 SF_Exception.RaiseFatal(NOTAFOLDERERROR,
"FolderName
", FolderName)
1860 SF_Exception.RaiseFatal(UNKNOWNFOLDERERROR,
"FolderName
", FolderName)
1862 End Function
' ScriptForge.SF_FileSystem.SubFolders
1864 REM =========================================================== PRIVATE FUNCTIONS
1866 REM -----------------------------------------------------------------------------
1867 Private Function _ConvertFromUrl(psFile) As String
1868 ''' Execute the builtin ConvertFromUrl function only when relevant
1869 ''' i.e. when FileNaming (how arguments and return values are provided) =
"SYS
"
1870 ''' Called at the bottom of methods returning file names
1871 ''' Remarks: psFile might contain wildcards
1872 ''' Files from document
's file systems are never converted
1874 Const cstQuestion =
"$QUESTION$
", cstStar =
"$STAR$
" ' Special tokens to replace wildcards
1876 If SF_FileSystem.FileNaming =
"SYS
" And Not SF_FileSystem._IsDocFileSystem(psFile) Then
1877 _ConvertFromUrl = Replace(Replace( _
1878 ConvertFromUrl(Replace(Replace(psFile,
"?
", cstQuestion),
"*
", cstStar)) _
1879 , cstQuestion,
"?
"), cstStar,
"*
")
1881 _ConvertFromUrl = psFile
1884 End Function
' ScriptForge.FileSystem._ConvertFromUrl
1886 REM -----------------------------------------------------------------------------
1887 Private Function _ConvertToUrl(psFile) As String
1888 ''' Execute the builtin ConvertToUrl function only when relevant
1889 ''' i.e. when FileNaming (how arguments and return values are provided)
<> "URL
"
1890 ''' Called at the top of methods receiving file names as arguments
1891 ''' Remarks: psFile might contain wildcards
1892 ''' Files from document
's file systems are never converted
1894 If SF_FileSystem.FileNaming =
"URL
" Or SF_FileSystem._IsDocFileSystem(psFile) Then
1895 _ConvertToUrl = psFile
1897 ' ConvertToUrl() encodes
"?
"
1898 _ConvertToUrl = Replace(ConvertToUrl(psFile),
"%
3F
",
"?
")
1901 End Function
' ScriptForge.FileSystem._ConvertToUrl
1903 REM -----------------------------------------------------------------------------
1904 Private Function _CopyMove(psMethod As String _
1905 , psSource As String _
1906 , psDestination As String _
1907 , pbOverWrite As Boolean _
1909 ''' Checks the arguments and executes the given method
1910 ''' Args:
1911 ''' psMethod: CopyFile/CopyFolder or MoveFile/MoveFolder
1912 ''' psSource: Either File/FolderName
1913 ''' or NamePattern which can include wildcard characters, for one or more files/folders to be copied
1914 ''' psDestination: FileName or FolderName for copy/move of a single file/folder
1915 ''' Otherwise a destination FolderName. If it does not exist, it is created
1916 ''' pbOverWrite: If True, files/folders may be overwritten
1917 ''' Must be False for Move operations
1918 ''' Next checks are done:
1919 ''' With wildcards (multiple files/folders):
1920 ''' - Parent folder of source must exist
1921 ''' - Destination must not be a file
1922 ''' - Parent folder of Destination must exist
1923 ''' - If the Destination folder does not exist a new folder is created,
1924 ''' - At least one file matches the wildcards expression
1925 ''' - Destination files/folder must not exist if pbOverWrite = False
1926 ''' - Destination files/folders must not have the read-only attribute set
1927 ''' - Destination files must not be folders, destination folders must not be files
1928 ''' Without wildcards (single file/folder):
1929 ''' - Source file/folder must exist and be a file/folder
1930 ''' - Parent folder of Destination must exist
1931 ''' - Destination must not be an existing folder/file
1932 ''' - Destination file/folder must not exist if pbOverWrite = False
1933 ''' - Destination file must not have the read-only attribute set
1935 Dim bCopyMove As Boolean
' Return value
1936 Dim bCopy As Boolean
' True if Copy, False if Move
1937 Dim bFile As Boolean
' True if File, False if Folder
1938 Dim oSfa As Object
' com.sun.star.ucb.SimpleFileAccess
1939 Dim bWildCards As Boolean
' True if wildcards found in Source
1940 Dim bCreateFolder As Boolean
' True when the destination folder should be created
1941 Dim bDestExists As Boolean
' True if destination exists
1942 Dim sSourceUrl As String
' Alias for Source
1943 Dim sDestinationUrl As String
' Alias for Destination
1944 Dim sDestinationFile As String
' Destination FileName
1945 Dim sParentFolder As String
' Parent folder of Source
1946 Dim vFiles As Variant
' Array of candidates for copy/move
1947 Dim sFile As String
' Single file/folder
1948 Dim sName As String
' Name (last component) of file
1951 ' Error handling left to calling routine
1953 bCopy = ( Left(psMethod,
4) =
"Copy
" )
1954 bFile = ( Right(psMethod,
4) =
"File
" )
1955 bWildCards = ( InStr(psSource,
"*
") + InStr(psSource,
"?
") + InStr(psSource,
"%
3F
")
> 0 )
'ConvertToUrl() converts sometimes
"?
" to
"%
3F
"
1962 sParentFolder = .GetParentFolderName(psSource)
1963 If Not .FolderExists(sParentFolder) Then GoTo CatchNoMatch
1964 If .FileExists(psDestination) Then GoTo CatchFileNotFolder
1965 If Not .FolderExists(.GetParentFolderName(psDestination)) Then GoTo CatchDestFolderNotExists
1966 bCreateFolder = Not .FolderExists(psDestination)
1969 Case True
' File
1970 If Not .FileExists(psSource) Then GoTo CatchFileNotExists
1971 If Not .FolderExists(.GetParentFolderName(psDestination)) Then GoTo CatchDestFolderNotExists
1972 If .FolderExists(psDestination) Then GoTo CatchFolderNotFile
1973 bDestExists = .FileExists(psDestination)
1974 If pbOverWrite = False And bDestExists = True Then GoTo CatchDestinationExists
1975 bCreateFolder = False
1976 Case False
' Folder
1977 If Not .FolderExists(psSource) Then GoTo CatchSourceFolderNotExists
1978 If Not .FolderExists(.GetParentFolderName(psDestination)) Then GoTo CatchDestFolderNotExists
1979 If .FileExists(psDestination) Then GoTo CatchFileNotFolder
1980 bDestExists = .FolderExists(psDestination)
1981 If pbOverWrite = False And bDestExists Then GoTo CatchDestinationExists
1982 bCreateFolder = Not bDestExists
1987 Set oSfa = SF_Utils._GetUnoService(
"FileAccess
")
1989 If bFile Then vFiles = .Files(sParentFolder, .GetName(psSource)) Else vFiles = .SubFolders(sParentFolder, .GetName(psSource))
1990 If UBound(vFiles)
< 0 Then GoTo CatchNoMatch
1991 ' Go through the candidates
1992 If bCreateFolder Then .CreateFolder(psDestination)
1993 For i =
0 To UBound(vFiles)
1995 sDestinationFile = .BuildPath(psDestination, .GetName(sFile))
1996 If bFile Then bDestExists = .FileExists(sDestinationFile) Else bDestExists = .FolderExists(sDestinationFile)
1997 If pbOverWrite = False Then
1998 If bDestExists Then GoTo CatchDestinationExists
1999 If .FolderExists(sDestinationFile) Then GoTo CatchDestinationExists
2001 sSourceUrl = ._ConvertToUrl(sFile)
2002 sDestinationUrl = ._ConvertToUrl(sDestinationFile)
2004 If oSfa.isReadOnly(sDestinationUrl) Then GoTo CatchDestinationReadOnly
2007 Case True : oSfa.copy(sSourceUrl, sDestinationUrl)
2008 Case False : oSfa.move(sSourceUrl, sDestinationUrl)
2012 sSourceUrl = ._ConvertToUrl(psSource)
2013 sDestinationUrl = ._ConvertToUrl(psDestination)
2015 If oSfa.isReadOnly(sDestinationUrl) Then GoTo CatchDestinationReadOnly
2017 If bCreateFolder Then .CreateFolder(psDestination)
2019 Case True : oSfa.copy(sSourceUrl, sDestinationUrl)
2020 Case False : oSfa.move(sSourceUrl, sDestinationUrl)
2029 _CopyMove = bCopyMove
2032 SF_Exception.RaiseFatal(UNKNOWNFILEERROR,
"Source
", psSource)
2034 CatchSourceFolderNotExists:
2035 SF_Exception.RaiseFatal(UNKNOWNFOLDERERROR,
"Source
", psSource)
2037 CatchDestFolderNotExists:
2038 SF_Exception.RaiseFatal(UNKNOWNFOLDERERROR,
"Destination
", psDestination)
2041 SF_Exception.RaiseFatal(NOTAFILEERROR,
"Destination
", psDestination)
2043 CatchDestinationExists:
2044 SF_Exception.RaiseFatal(OVERWRITEERROR,
"Destination
", psDestination)
2047 SF_Exception.RaiseFatal(NOFILEMATCHERROR,
"Source
", psSource)
2050 SF_Exception.RaiseFatal(NOTAFOLDERERROR,
"Destination
", psDestination)
2052 CatchDestinationReadOnly:
2053 SF_Exception.RaiseFatal(READONLYERROR,
"Destination
", Iif(bWildCards, sDestinationFile, psDestination))
2055 End Function
' ScriptForge.SF_FileSystem._CopyMove
2057 REM -----------------------------------------------------------------------------
2058 Public Function _CountTextLines(ByVal psFileName As String _
2059 , Optional ByVal pbIncludeBlanks As Boolean _
2061 ''' Convenient function to count the number of lines in a textfile
2062 ''' Args:
2063 ''' psFileName: the file in FileNaming notation
2064 ''' pbIncludeBlanks: if True (default), zero-length lines are included
2065 ''' Returns:
2066 ''' The number of lines, f.i. to ease array sizing. -
1 if file reading error
2068 Dim lLines As Long
' Return value
2069 Dim oFile As Object
' File handler
2070 Dim sLine As String
' The last line read
2074 If IsMissing(pbIncludeBlanks) Then pbIncludeBlanks = True
2075 Set oFile = SF_FileSystem.OpenTextFile(psFileName, ForReading)
2077 If Not IsNull(oFile) Then
2078 Do While Not .AtEndOfStream
2080 lLines = lLines + Iif(Len(sLine)
> 0 Or pbIncludeBlanks,
1,
0)
2084 Set oFile = .Dispose()
2088 _CountTextLines = lLines
2090 End Function
' ScriptForge.SF_FileSystem._CountTextLines
2092 REM -----------------------------------------------------------------------------
2093 Private Function _Delete(psMethod As String _
2094 , psFile As String _
2096 ''' Checks the argument and executes the given psMethod
2097 ''' Args:
2098 ''' psMethod: CopyFile/CopyFolder or MoveFile/MoveFolder
2099 ''' psFile: Either File/FolderName
2100 ''' or NamePattern which can include wildcard characters, for one or more files/folders to be deleted
2101 ''' Next checks are done:
2102 ''' With wildcards (multiple files/folders):
2103 ''' - Parent folder of File must exist
2104 ''' - At least one file matches the wildcards expression
2105 ''' - Files or folders to delete must not have the read-only attribute set
2106 ''' Without wildcards (single file/folder):
2107 ''' - File/folder must exist and be a file/folder
2108 ''' - A file or folder to delete must not have the read-only attribute set
2110 Dim bDelete As Boolean
' Return value
2111 Dim bFile As Boolean
' True if File, False if Folder
2112 Dim oSfa As Object
' com.sun.star.ucb.SimpleFileAccess
2113 Dim bWildCards As Boolean
' True if wildcards found in File
2114 Dim sFileUrl As String
' Alias for File
2115 Dim sParentFolder As String
' Parent folder of File
2116 Dim vFiles As Variant
' Array of candidates for deletion
2117 Dim sFile As String
' Single file/folder
2118 Dim sName As String
' Name (last component) of file
2121 ' Error handling left to calling routine
2123 bFile = ( Right(psMethod,
4) =
"File
" )
2124 bWildCards = ( InStr(psFile,
"*
") + InStr(psFile,
"?
") + InStr(psFile,
"%
3F
")
> 0 )
'ConvertToUrl() converts sometimes
"?
" to
"%
3F
"
2130 sParentFolder = .GetParentFolderName(psFile)
2131 If Not .FolderExists(sParentFolder) Then GoTo CatchNoMatch
2134 Case True
' File
2135 If .FolderExists(psFile) Then GoTo CatchFolderNotFile
2136 If Not .FileExists(psFile) Then GoTo CatchFileNotExists
2137 Case False
' Folder
2138 If .FileExists(psFile) Then GoTo CatchFileNotFolder
2139 If Not .FolderExists(psFile) Then GoTo CatchFolderNotExists
2144 Set oSfa = SF_Utils._GetUnoService(
"FileAccess
")
2146 If bFile Then vFiles = .Files(sParentFolder) Else vFiles = .SubFolders(sParentFolder)
2147 ' Select candidates
2148 For i =
0 To UBound(vFiles)
2149 If Not SF_String.IsLike(.GetName(vFiles(i)), .GetName(psFile)) Then vFiles(i) =
""
2151 vFiles = SF_Array.TrimArray(vFiles)
2152 If UBound(vFiles)
< 0 Then GoTo CatchNoMatch
2153 ' Go through the candidates
2154 For i =
0 To UBound(vFiles)
2156 sFileUrl = ._ConvertToUrl(sFile)
2157 If oSfa.isReadOnly(sFileUrl) Then GoTo CatchReadOnly
2161 sFileUrl = ._ConvertToUrl(psFile)
2162 If oSfa.isReadOnly(sFileUrl) Then GoTo CatchReadOnly
2173 CatchFolderNotExists:
2174 SF_Exception.RaiseFatal(UNKNOWNFOLDERERROR,
"FolderName
", psFile)
2177 SF_Exception.RaiseFatal(UNKNOWNFILEERROR,
"FileName
", psFile)
2180 SF_Exception.RaiseFatal(NOTAFILEERROR,
"FileName
", psFile)
2183 SF_Exception.RaiseFatal(NOFILEMATCHERROR, Iif(bFile,
"FileName
",
"FolderName
"), psFile)
2186 SF_Exception.RaiseFatal(NOTAFOLDERERROR,
"FolderName
", psFile)
2189 SF_Exception.RaiseFatal(READONLYERROR, Iif(bFile,
"FileName
",
"FolderName
"), Iif(bWildCards, sFile, psFile))
2191 End Function
' ScriptForge.SF_FileSystem._Delete
2193 REM -----------------------------------------------------------------------------
2194 Private Function _GetConfigFolder(ByVal psFolder As String) As String
2195 ''' Returns one of next configuration folders: see https://api.libreoffice.org/docs/idl/ref/servicecom_1_1sun_1_1star_1_1util_1_1PathSubstitution.html
2196 ''' inst =
> Installation path of LibreOffice
2197 ''' prog =
> Program path of LibreOffice
2198 ''' user =
> The user installation/config directory
2199 ''' work =
> The work directory of the user. Under Windows this would be the
"MyDocuments
" subdirectory. Under Unix this would be the home-directory
2200 ''' home =
> The home directory of the user. Under Unix this would be the home- directory.
2201 ''' Under Windows this would be the CSIDL_PERSONAL directory, for example
"Documents and Settings\
<username
>\Documents
"
2202 ''' temp =
> The current temporary directory
2204 Dim oSubst As Object
' com.sun.star.util.PathSubstitution
2205 Dim sConfig As String
' Return value
2207 sConfig =
""
2208 Set oSubst = SF_Utils._GetUNOService(
"PathSubstitution
")
2209 If Not IsNull(oSubst) Then sConfig = oSubst.getSubstituteVariableValue(
"$(
" & psFolder
& ")
")
& "/
"
2211 _GetConfigFolder = SF_FileSystem._ConvertFromUrl(sConfig)
2213 End Function
' ScriptForge.FileSystem._GetConfigFolder
2215 REM -----------------------------------------------------------------------------
2216 Public Function _IsDocFileSystem(psFile As String) As Boolean
2217 ''' Returns True when the argument designates a document
's internal file system
2219 _IsDocFileSystem = SF_String.StartsWith(psFile, DOCFILESYSTEM, CaseSensitive := True)
2221 End Function
' ScriptForge.SF_FileSystem._IsDocFileSystem
2223 REM -----------------------------------------------------------------------------
2224 Private Sub _ScanFolder(ByVal piTarget As Integer _
2225 , ByRef psItemsColl As String _
2226 , ByVal psFolderName As String _
2227 , ByRef poSfa As Object _
2228 , ByVal psFilter As String _
2229 , ByVal pbIncludeSubFolders As Boolean _
2231 ''' Scan a folder and, when requested, its subfolders recursively.
2232 ''' The psItemsColl in-out argument concatenates, depending on the target,
2233 ''' either all files or all folders found.
2234 ''' The Sub calls itself recursively when relevant.
2235 ''' Args:
2236 ''' piTarget:
1 when caller routine = Files(),
2 when caller routine = SubFolders()
2237 ''' It determines the type of items to collect: files or folders
2238 ''' psItemsColl: the current and future list of folders or files (FileNaming format) separated with cstSEPARATOR
2239 ''' psFolderName: the folder to scan (FileNaming format)
2240 ''' poSfa: com.sun.star.ucb.SimpleFileAccess
2241 ''' psFilter: contains wildcards (
"?
" and
"*
") to limit the list to the relevant folders or files.
2242 ''' Zero-length string when not applicable.
2243 ''' pbIncludeSubfolders: when True, subfolders are explored too.
2245 Dim vSubFolders As Variant
' Array of subfolders
1st level in URL notation
2246 Dim vFiles As Variant
' Array of files present in psFolderName in FileNaming notation
2247 Dim lFiles As Long
' Number of files found passing the filter
2248 Dim sFolderName As String
' URL alias for psFolderName
2249 Dim sItem As String
' Single folder or single file in FileNaming notation
2250 Dim sItemName As String
' Base name of sItem
2251 Dim bFolder As Boolean
' When True, the considered string points to a folder, not a file
2252 Dim bFilter As Boolean
' When True, no filter or the filter is passed
2256 On Local Error Goto catch
2261 ' Get SubFolders, initialize files list
2262 sFolderName = SF_FileSystem._ConvertToUrl(psFolderName)
2263 vSubFolders = .getFolderContents(sFolderName, True)
2264 If UBound(vSubFolders)
< 0 Then Exit Sub
2266 If piTarget = cstFiles Then
2268 ReDim vFiles(
0 To UBound(vSubFolders))
2271 ' List includes files: remove them or adjust notations of folders
2272 ' When piTarget = cstFiles, the list of files is stored in the vFiles() array
2273 For i =
0 To UBound(vSubFolders)
2274 sItem = SF_FileSystem._ConvertFromUrl(vSubFolders(i))
2275 bFolder = .isFolder(vSubFolders(i))
2276 Select Case piTarget
2279 vSubFolders(i) = sItem
& "/
"
2281 ' Build list of files passing the filter
2282 bFilter = ( Len(psFilter) =
0 )
2284 sItemName = SF_FileSystem.GetName(sItem)
2285 bFilter = SF_String.IsLike(sItemName, psFilter)
2287 If bFilter Then
' Copy files from folders + files list
2288 vFiles(lFiles) = sItem
2291 vSubFolders(i) =
"" ' Keep folders only
2294 If bFolder Then vSubFolders(i) = sItem
& "/
" Else vSubFolders(i) =
""
2295 ' Reduce list to those passing the filter
2296 If Len(psFilter)
> 0 And Len(vSubFolders(i))
> 0 Then
2297 sItemName = SF_FileSystem.GetName(sItem)
2298 If Not SF_String.IsLike(sItemName, psFilter) Then vSubFolders(i) =
""
2302 vSubFolders = SF_Array.TrimArray(vSubFolders)
2304 ' Store the list of either files or subfolders in the global collection
2305 Select Case piTarget
2307 If lFiles
> 0 Then
2308 ReDim Preserve vFiles(
0 To lFiles -
1)
2309 psItemsColl = psItemsColl
& cstSEPARATOR
& Join(vFiles, cstSEPARATOR)
2312 If UBound(vSubFolders)
>=
0 Then psItemsColl = psItemsColl
& cstSEPARATOR
& Join(vSubFolders, cstSEPARATOR)
2315 ' Scan each subfolder when relevant
2316 If pbIncludeSubfolders Then
2317 For i =
0 To UBound(vSubFolders)
2318 _ScanFolder(piTarget, psItemsColl, vSubFolders(i), poSfa, psFilter, True)
2327 SF_Exception.Clear()
2328 psItemsColl =
""
2330 End Sub
' ScriptForge.SF_FileSystem._ScanFolder
2332 REM -----------------------------------------------------------------------------
2333 Public Function _ParseUrl(psUrl As String) As Object
2334 ''' Returns a com.sun.star.util.URL structure based on the argument
2336 Dim oParse As Object
' com.sun.star.util.URLTransformer
2337 Dim bParsed As Boolean
' True if parsing is successful
2338 Dim oUrl As New com.sun.star.util.URL
' Return value
2340 oUrl.Complete = psUrl
2341 Set oParse = SF_Utils._GetUNOService(
"URLTransformer
")
2342 bParsed = oParse.parseStrict(oUrl,
"")
2343 If bParsed Then oUrl.Path = ConvertToUrl(oUrl.Path)
2345 Set _ParseUrl = oUrl
2347 End Function
' ScriptForge.SF_FileSystem._ParseUrl
2349 REM -----------------------------------------------------------------------------
2350 Public Function _SFInstallFolder() As String
2351 ''' Returns the installation folder of the ScriptForge library
2352 ''' Either:
2353 ''' - The library is present in [My Macros
& Dialogs]
2354 ''' ($config)/basic/ScriptForge
2355 ''' - The library is present in [LibreOffice Macros
& Dialogs]
2356 ''' ($install)/share/basic/ScriptForge
2358 Dim sFolder As String
' Folder
2360 _SFInstallFolder =
""
2362 sFolder = BuildPath(ConfigFolder,
"basic/ScriptForge
")
2363 If Not FolderExists(sFolder) Then
2364 sFolder = BuildPath(InstallFolder,
"share/basic/ScriptForge
")
2365 If Not FolderExists(sFolder) Then Exit Function
2368 _SFInstallFolder = _ConvertFromUrl(sFolder)
2370 End Function
' ScriptForge.SF_FileSystem._SFInstallFolder
2372 REM ============================================ END OF SCRIPTFORGE.SF_FileSystem