fsharp 文件结构2

本文介绍了一种使用匹配表达式进行文件系统操作的方法,包括获取指定路径下的文件和目录信息,并实现文件复制及备份功能。该方法通过递归方式处理目录和文件,支持将源路径下的文件结构完整复制到目标路径。
open System
open System.IO


type FileUnit = 
    | Empty 
    | FileElem of string * FileAttributes
    | DirectoryElem of string * FileAttributes * FileUnit
    | FDList of seq<FileUnit>




let rec getFiles path =
    match DirectoryInfo(path).Exists with
    | false -> Empty
    | _     -> match DirectoryInfo(path).Attributes &&& FileAttributes.Directory with
               | FileAttributes.Directory -> let dflst = 
                                                        match Directory.GetFiles(path).Length, Directory.GetDirectories(path).Length with
                                                        |0, 0 -> Empty
                                                        |1, 0 -> let tpath = Directory.GetFiles(path).[0]
                                                                 FileElem(tpath, DirectoryInfo(tpath).Attributes)
                                                        |0, 1 -> let tpath = Directory.GetDirectories(path).[0]
                                                                 tpath |> getFiles
                                                        |_, _ -> FDList(seq{for elem in Directory.GetFiles(path) do
                                                                                yield FileElem(elem, DirectoryInfo(elem).Attributes)
                                                                            for elem in Directory.GetDirectories(path) do
                                                                                yield elem |> getFiles})
                                             DirectoryElem(path, DirectoryInfo(path).Attributes, dflst)
               | _ -> FileElem(path, DirectoryInfo(path).Attributes)


let rec copyfile (sourcepath:string) (destpath:string) ignorelst plst= 
    match plst with
    |Empty -> ()
    |FileElem(path, _) -> File.Copy(path, path.Replace(sourcepath, destpath), true)
    |DirectoryElem(path, _, lst) ->
                 if (not (Seq.exists (fun elem -> elem = DirectoryInfo(path).Name.ToLower()) ignorelst)) then
                    Directory.CreateDirectory(path.Replace(sourcepath, destpath)) |> ignore
                    copyfile sourcepath destpath ignorelst lst
    |FDList lst -> for elem in lst do
                       copyfile sourcepath destpath ignorelst elem


let backupfile (sourcepath:string) (destpath:string) ignorelst=
    getFiles sourcepath
    |> copyfile sourcepath destpath ignorelst

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值