WIP: cleanup, work on doc result form
This commit is contained in:
232
Modules.Filesystem/File.vb
Normal file
232
Modules.Filesystem/File.vb
Normal file
@@ -0,0 +1,232 @@
|
||||
Imports System.IO
|
||||
Imports DigitalData.Modules.Logging
|
||||
|
||||
''' <module>File</module>
|
||||
''' <version>0.0.0.1</version>
|
||||
''' <date>11.10.2018</date>
|
||||
''' <summary>
|
||||
''' Module that provides variouse File operations
|
||||
''' </summary>
|
||||
''' <dependencies>
|
||||
''' NLog, >= 4.5.8
|
||||
''' </dependencies>
|
||||
''' <params>
|
||||
''' LogConfig, DigitalData.Module.Logging.LogConfig
|
||||
''' A LogConfig object
|
||||
''' </params>
|
||||
''' <props>
|
||||
''' </props>
|
||||
''' <example>
|
||||
''' </example>
|
||||
''' <remarks>
|
||||
''' </remarks>
|
||||
Public Class File
|
||||
Private ReadOnly _logger As Logger
|
||||
Private ReadOnly _logConfig As LogConfig
|
||||
|
||||
Private Const FILE_NAME_ACCESS_TEST = "accessTest.txt"
|
||||
|
||||
Public Sub New(LogConfig As LogConfig)
|
||||
_logConfig = LogConfig
|
||||
_logger = LogConfig.GetLogger()
|
||||
End Sub
|
||||
|
||||
''' <summary>
|
||||
''' Adds fileversions to given filename `Destination` if that file already exists.
|
||||
''' </summary>
|
||||
''' <param name="Destination"></param>
|
||||
''' <returns></returns>
|
||||
Public Function GetVersionedFilename(Destination As String) As String
|
||||
Try
|
||||
Dim oFileName As String = Destination
|
||||
Dim oFinalFileName = oFileName
|
||||
|
||||
Dim oDestinationDir = Path.GetDirectoryName(oFileName)
|
||||
Dim oExtension = Path.GetExtension(oFileName)
|
||||
|
||||
Dim oVersionSeparator As Char = "~"c
|
||||
Dim oFileVersion As Integer = Nothing
|
||||
|
||||
' Split Filename without extension at version separator to:
|
||||
' - Check if file is already versioned
|
||||
' - Get the file version of an already versioned file
|
||||
'
|
||||
' Example:
|
||||
' test1.pdf --> test1 --> ['test1'] --> no fileversion
|
||||
' test1~2.pdf --> test1~2 --> ['test1', '2'] --> version 2
|
||||
' test1~12345~2.pdf --> test1~12345~2 --> ['test1', '12345', '2'] --> still version 2
|
||||
Dim oFileNameWithoutExtension = Path.GetFileNameWithoutExtension(oFileName)
|
||||
Dim oSplitFilename = oFileNameWithoutExtension.Split(oVersionSeparator).ToList()
|
||||
|
||||
' if file is already versioned, extract file version
|
||||
' else just use the filename and set version to 1
|
||||
If oSplitFilename.Count > 1 Then
|
||||
Dim oVersion As Integer = 1
|
||||
Try
|
||||
oVersion = Integer.Parse(oSplitFilename.Last())
|
||||
Catch ex As Exception
|
||||
' oFilenameWithoutExtension does NOT change
|
||||
oFileNameWithoutExtension = oFileNameWithoutExtension
|
||||
Finally
|
||||
oFileVersion = oVersion
|
||||
End Try
|
||||
Else
|
||||
oFileVersion = 1
|
||||
oFileNameWithoutExtension = String.Join(String.Empty, oSplitFilename.Take(oSplitFilename.Count - 1))
|
||||
End If
|
||||
|
||||
' while file exists, increment version
|
||||
Do
|
||||
oFinalFileName = Path.Combine(oDestinationDir, GetFilenameWithVersion(oFileNameWithoutExtension, oVersionSeparator, oFileVersion, oExtension))
|
||||
_logger.Debug("Intermediate Filename is {0}", oFinalFileName)
|
||||
_logger.Debug("File version: {0}", oFileVersion)
|
||||
oFileVersion += 1
|
||||
Loop While (IO.File.Exists(oFinalFileName))
|
||||
|
||||
_logger.Debug("Final Filename is {0}", oFinalFileName)
|
||||
|
||||
Return oFinalFileName
|
||||
Catch ex As Exception
|
||||
_logger.Warn("Filename {0} could not be versioned. Original filename will be returned!", Destination)
|
||||
_logger.Error(ex)
|
||||
Return Destination
|
||||
End Try
|
||||
End Function
|
||||
|
||||
Private Function GetFilenameWithVersion(FileNameWithoutExtension As String, VersionSeparator As Char, FileVersion As Integer, Extension As String) As String
|
||||
If FileVersion <= 1 Then
|
||||
Return $"{FileNameWithoutExtension}{Extension}"
|
||||
Else
|
||||
Return $"{FileNameWithoutExtension}{VersionSeparator}{FileVersion}{Extension}"
|
||||
End If
|
||||
End Function
|
||||
|
||||
''' <summary>
|
||||
''' Removes files in a directory filtered by filename, extension and last write date
|
||||
''' </summary>
|
||||
''' <param name="Path">The directory in which files will be deleted</param>
|
||||
''' <param name="FileKeepTime">Only delete files which are older than x days. Must be between 0 and 1000 days.</param>
|
||||
''' <param name="FileBaseName">A filename filter which will be checked</param>
|
||||
''' <param name="FileExtension">A file extension which will be checked</param>
|
||||
''' <param name="ContinueOnError">Should the function continue with deleting when a file could not be deleted?</param>
|
||||
''' <returns>True if all files were deleted or if no files were deleted, otherwise false</returns>
|
||||
Public Function RemoveFiles(Path As String, FileKeepTime As Integer, FileBaseName As String, Optional FileExtension As String = "log", Optional ContinueOnError As Boolean = True) As Boolean
|
||||
If Not TestPathIsDirectory(Path) Then
|
||||
Throw New ArgumentException($"Path {Path} is not a directory!")
|
||||
End If
|
||||
|
||||
If Not Directory.Exists(Path) Then
|
||||
Throw New DirectoryNotFoundException($"Path {Path} does not exist!")
|
||||
End If
|
||||
|
||||
If FileKeepTime < 0 Or FileKeepTime > 1000 Then
|
||||
Throw New ArgumentOutOfRangeException("FileKeepTime must be an integer between 0 and 1000!")
|
||||
End If
|
||||
|
||||
Dim oUnableToDeleteCounter = 0
|
||||
Dim oDirectory As New DirectoryInfo(Path)
|
||||
Dim oDateLimit As DateTime = DateTime.Now.AddDays(FileKeepTime)
|
||||
Dim oFiles As List(Of FileInfo) = oDirectory.
|
||||
EnumerateFiles($"*{FileBaseName}*").
|
||||
Where(Function(oFileInfo As FileInfo)
|
||||
Return oFileInfo.Extension = FileExtension And oFileInfo.LastWriteTime < oDateLimit
|
||||
End Function)
|
||||
|
||||
If oFiles.Count = 0 Then
|
||||
_logger.Debug("No files found that match the criterias.")
|
||||
Return True
|
||||
End If
|
||||
|
||||
_logger.Debug("Deleting old files (Found {0}).", oFiles.Count)
|
||||
|
||||
For Each oFile As FileInfo In oFiles
|
||||
Try
|
||||
oFile.Delete()
|
||||
Catch ex As Exception
|
||||
If ContinueOnError = False Then
|
||||
_logger.Warn("Deleting files was aborted at file {0}.", oFile.FullName)
|
||||
Return False
|
||||
End If
|
||||
oUnableToDeleteCounter = oUnableToDeleteCounter + 1
|
||||
_logger.Warn("File {0} could not be deleted!")
|
||||
End Try
|
||||
Next
|
||||
|
||||
If oUnableToDeleteCounter > 0 Then
|
||||
_logger.Debug("Old files partially removed. {0} files could not be removed.", oUnableToDeleteCounter)
|
||||
Else
|
||||
_logger.Debug("Old files removed.")
|
||||
End If
|
||||
|
||||
Return True
|
||||
End Function
|
||||
|
||||
Public Sub MoveTo(FilePath As String, Directory As String)
|
||||
Dim oFileInfo As New FileInfo(FilePath)
|
||||
IO.File.Move(FilePath, Path.Combine(Directory, oFileInfo.Name))
|
||||
End Sub
|
||||
|
||||
Public Sub MoveTo(FilePath As String, NewFileName As String, Directory As String)
|
||||
Dim oFileInfo As New FileInfo(FilePath)
|
||||
IO.File.Move(FilePath, Path.Combine(Directory, NewFileName))
|
||||
End Sub
|
||||
|
||||
''' <summary>
|
||||
''' Tries to create a directory and returns its path.
|
||||
''' Returns a temp path if `DirectoryPath` can not be created or written to.
|
||||
''' </summary>
|
||||
''' <param name="DirectoryPath">The directory to create</param>
|
||||
''' <param name="TestWriteAccess">Should a write access test be performed?</param>
|
||||
''' <returns>The used path</returns>
|
||||
Public Function CreateDirectory(DirectoryPath As String, Optional TestWriteAccess As Boolean = True) As String
|
||||
Dim oFinalPath As String
|
||||
If Directory.Exists(DirectoryPath) Then
|
||||
_logger.Debug("Directory {0} already exists. Skipping.", DirectoryPath)
|
||||
oFinalPath = DirectoryPath
|
||||
Else
|
||||
Try
|
||||
Directory.CreateDirectory(DirectoryPath)
|
||||
oFinalPath = DirectoryPath
|
||||
Catch ex As Exception
|
||||
_logger.Error(ex)
|
||||
_logger.Warn("Directory {0} could not be created. Temp path will be used instead.", DirectoryPath)
|
||||
oFinalPath = Path.GetTempPath()
|
||||
End Try
|
||||
End If
|
||||
|
||||
If TestWriteAccess AndAlso Not TestPathIsWritable(DirectoryPath) Then
|
||||
_logger.Warn("Directory {0} is not writable. Temp path will be used instead.", DirectoryPath)
|
||||
oFinalPath = Path.GetTempPath()
|
||||
Else
|
||||
oFinalPath = DirectoryPath
|
||||
End If
|
||||
|
||||
_logger.Debug("Using path {0}", oFinalPath)
|
||||
|
||||
Return oFinalPath
|
||||
End Function
|
||||
|
||||
Public Function TestPathIsWritable(DirectoryPath As String) As Boolean
|
||||
Try
|
||||
Dim fileAccessPath = Path.Combine(DirectoryPath, FILE_NAME_ACCESS_TEST)
|
||||
Using fs As FileStream = IO.File.Create(fileAccessPath)
|
||||
fs.WriteByte(0)
|
||||
End Using
|
||||
|
||||
IO.File.Delete(fileAccessPath)
|
||||
Return True
|
||||
Catch ex As Exception
|
||||
Return False
|
||||
End Try
|
||||
End Function
|
||||
|
||||
Public Function TestPathIsDirectory(Path As String) As Boolean
|
||||
If Not Directory.Exists(Path) Then
|
||||
Return False
|
||||
End If
|
||||
|
||||
Dim oIsDirectory As Boolean = (System.IO.File.GetAttributes(Path) And FileAttributes.Directory) = FileAttributes.Directory
|
||||
Return oIsDirectory
|
||||
End Function
|
||||
|
||||
End Class
|
||||
Reference in New Issue
Block a user