github.com/sandwich-go/boost@v1.3.29/xos/hide.windows.go (about)

     1  //go:build windows
     2  // +build windows
     3  
     4  package xos
     5  
     6  import (
     7  	"os"
     8  	"syscall"
     9  )
    10  
    11  func getFileAttrs(path string) (uint32, *uint16, error) {
    12  	utf16PtrPath, err := syscall.UTF16PtrFromString(path)
    13  	if err != nil {
    14  		return 0, nil, err
    15  	}
    16  	var attrs uint32
    17  	attrs, err = syscall.GetFileAttributes(utf16PtrPath)
    18  	return attrs, utf16PtrPath, err
    19  }
    20  
    21  // IsHidden 判断是否为隐藏文件
    22  func IsHidden(path string) (bool, error) {
    23  	_, err := os.Stat(path)
    24  	if err != nil {
    25  		return false, err
    26  	}
    27  	var attrs uint32
    28  	attrs, _, err = getFileAttrs(path)
    29  	if err != nil {
    30  		return false, err
    31  	}
    32  	return attrs&syscall.FILE_ATTRIBUTE_HIDDEN > 0, nil
    33  }
    34  
    35  func hide(path string, hidden bool) error {
    36  	isHidden, err := IsHidden(path)
    37  	if err != nil || hidden == isHidden {
    38  		return err
    39  	}
    40  	var attrs uint32
    41  	var utf16PtrPath *uint16
    42  	attrs, utf16PtrPath, err = getFileAttrs(path)
    43  	if err != nil {
    44  		return err
    45  	}
    46  
    47  	var newAttrs uint32
    48  	if hidden {
    49  		if attrs&syscall.FILE_ATTRIBUTE_HIDDEN > 0 {
    50  			return nil
    51  		}
    52  		newAttrs = attrs | syscall.FILE_ATTRIBUTE_HIDDEN
    53  	} else {
    54  		if attrs&syscall.FILE_ATTRIBUTE_HIDDEN == 0 {
    55  			return nil
    56  		}
    57  		newAttrs = attrs - (attrs & syscall.FILE_ATTRIBUTE_HIDDEN)
    58  	}
    59  	return syscall.SetFileAttributes(utf16PtrPath, newAttrs)
    60  }
    61  
    62  // Hide 隐藏指定文件,返回被隐藏文件的名称
    63  func Hide(path string) (string, error) {
    64  	return path, hide(path, true)
    65  }
    66  
    67  // ForceHide 隐藏指定文件,返回被隐藏文件的名称
    68  func ForceHide(path string) (string, error) {
    69  	return Hide(path)
    70  }
    71  
    72  // UnHide 取消隐藏指定文件,返回被取消隐藏文件的名称
    73  func UnHide(path string) (string, error) {
    74  	return path, hide(path, false)
    75  }
    76  
    77  // ForceUnHide 取消隐藏指定文件,返回被取消隐藏文件的名称
    78  func ForceUnHide(path string) (string, error) {
    79  	return UnHide(path)
    80  }