Jump to content

Check write permission


Recommended Posts

Snippet of what? I have ask a question and i expect an answer like "use this API-function" because i don't have found nothing except check error code if the function fail example FileOpen/IniWrite and so on.

Nothing is so strong as gentleness. Nothing is so gentle as real strength

 

Link to comment
Share on other sites

You can do this.

 

I don't have time to traslate it to AutoIt . but it's easy.

 

Regards

Link to comment
Share on other sites

Maybe this UDF helps

 

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

following this:

this is a rephrasing of mine. it works with files as well as folders, local and network - and even knows when elevation is required. try this - uncomment the first line:

; #RequireAdmin
MsgBox(0, '', _PathIsWritable(@SystemDir) & @CRLF) ; without @RequireAdmin this should return False, with @RequireAdmin this should return True.

Func _PathIsWritable($sFile)
    Local $aRet = DllCall('kernel32.dll', 'handle', 'CreateFileW', _
            'wstr', $sFile, _
            'dword', 2, _
            'dword', 7, _
            'struct*', 0, _
            'dword', 3, _
            'dword', 0x02000000, _
            'handle', 0)
    If @error Or $aRet[0] = Ptr(-1) Or $aRet[0] = 0 Then Return False
    DllCall('kernel32.dll', 'bool', 'CloseHandle', 'handle', $aRet[0])
    Return True
EndFunc   ;==>_PathIsWritable

z

Signature - my forum contributions:

Spoiler

UDF:

LFN - support for long file names (over 260 characters)

InputImpose - impose valid characters in an input control

TimeConvert - convert UTC to/from local time and/or reformat the string representation

AMF - accept multiple files from Windows Explorer context menu

DateDuration -  literal description of the difference between given dates

Apps:

Touch - set the "modified" timestamp of a file to current time

Show For Files - tray menu to show/hide files extensions, hidden & system files, and selection checkboxes

SPDiff - Single-Pane Text Diff

 

Link to comment
Share on other sites

@orbs I would prefer you use the _WinAPI_* associated calls than DllCall, as not everyone is familiar with these.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Danyfirex,

I'm not able to convert that. When you have time, for future reference...

Orbs,

Really a fast and easy solution using _WinAPI_CreateFileEx() thanks to all

Edited by Terenz

Nothing is so strong as gentleness. Nothing is so gentle as real strength

 

Link to comment
Share on other sites

Hello. Here you have.

 

#include <WinAPIProc.au3>
#include <WinAPI.au3>
Opt("MustDeclareVars", 1)
#RequireAdmin
Global Const $OWNER_SECURITY_INFORMATION = 0x1
Global Const $GROUP_SECURITY_INFORMATION = 0x2
Global Const $DACL_SECURITY_INFORMATION = 0x4
Global Const $FILE_GENERIC_READ = 0x120089 ;STANDARD_RIGHTS_READ Or FILE_READ_DATA Or FILE_READ_ATTRIBUTES Or _FILE_READ_EA Or SYNCHRONIZE
Global Const $FILE_GENERIC_WRITE = 0x120116 ;STANDARD_RIGHTS_WRITE Or FILE_WRITE_DATA Or FILE_WRITE_ATTRIBUTES Or _FILE_WRITE_EA Or FILE_APPEND_DATA Or SYNCHRONIZE
Global Const $FILE_GENERIC_EXECUTE = 0x1200A0 ;STANDARD_RIGHTS_EXECUTE Or FILE_READ_ATTRIBUTES Or FILE_EXECUTE Or SYNCHRONIZE
Global Const $FILE_ALL_ACCESS = 0x1F01FF ;STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or &H1FF
Global Const $sTag_GENERIC_MAPPING = "dword GenericRead;dword GenericWrite;dword GenericExecute;dword GenericAll;"





If _CanAccessFolder("C:\System Volume Information", $GENERIC_WRITE) Then
    MsgBox(0, ":)", "I can Write...")
Else
    MsgBox(0, ":(", "I can't Write...")
EndIf


If _CanAccessFolder("C:\", $GENERIC_WRITE) Then
    MsgBox(0, ":)", "I can Write...")
Else
    MsgBox(0, ":(", "I can't Write...")
EndIf


Func _CanAccessFolder($sDir, $genericAccessRights)
    Local $bRet = False


    Local $tSecurityDescriptor = _GetSecurityDescriptor($sDir)
    ConsoleWrite("$tSecurityDescriptor: " & DllStructGetData($tSecurityDescriptor, 1) & @CRLF)

    Local $hToken = _WinAPI_OpenProcessToken(BitOR($TOKEN_IMPERSONATE, $TOKEN_QUERY, $TOKEN_DUPLICATE, $STANDARD_RIGHTS_READ))

    ConsoleWrite("$hToken: " & $hToken & @CRLF)

    Local $hImpersonatedToken = _WinAPI_DuplicateTokenEx($hToken, 0, $SECURITYIMPERSONATION, $TOKENIMPERSONATION)
    ConsoleWrite("$hImpersonatedToken: " & $hImpersonatedToken & @CRLF)

    Local $tmapping = DllStructCreate($sTag_GENERIC_MAPPING)

    $tmapping.GenericRead = $FILE_GENERIC_READ
    $tmapping.GenericWrite = $FILE_GENERIC_WRITE
    $tmapping.GenericExecute = $FILE_GENERIC_EXECUTE
    $tmapping.GenericAll = $FILE_ALL_ACCESS

    _MapGenericMask($tmapping, $genericAccessRights)
    ConsoleWrite("$genericAccessRights: " & $genericAccessRights & @CRLF)

    Local $tprivilege_set = DllStructCreate("dword;dword;dword;dword;dword")

    Local $aRet = DllCall("Advapi32.dll", "bool", "AccessCheck", "ptr", DllStructGetPtr($tSecurityDescriptor), "handle", $hImpersonatedToken, "dword", $genericAccessRights, _
            "ptr", DllStructGetPtr($tmapping), "ptr", DllStructGetPtr($tprivilege_set), "dword*", DllStructGetSize($tprivilege_set), "dword*", 0, "bool*", 0)

    $bRet = $aRet[8]

    If $hImpersonatedToken Then _WinAPI_CloseHandle($hImpersonatedToken)
    If $hToken Then _WinAPI_CloseHandle($hToken)


    Return $bRet

EndFunc   ;==>_CanAccessFolder












Func _GetSecurityDescriptor($sDir)
    Local $aRet = DllCall("Advapi32.dll", "bool", "GetFileSecurityW", _
            "wstr", $sDir, _
            "dword", BitOR($OWNER_SECURITY_INFORMATION, $GROUP_SECURITY_INFORMATION, $DACL_SECURITY_INFORMATION), _
            "ptr", Null, _
            "dword", Null, _
            "dword*", 0)

    Local $iBufferSize = $aRet[5]

    ConsoleWrite("$iNeededSize: " & $iBufferSize & @CRLF)

    Local $tSecurityDescriptor = DllStructCreate("byte[" & $iBufferSize & "]")

    $aRet = DllCall("Advapi32.dll", "bool", "GetFileSecurityW", _
            "wstr", $sDir, _
            "dword", BitOR($OWNER_SECURITY_INFORMATION, $GROUP_SECURITY_INFORMATION, $DACL_SECURITY_INFORMATION), _
            "ptr", DllStructGetPtr($tSecurityDescriptor), _
            "dword", $iBufferSize, _
            "dword*", 0)
    Return $tSecurityDescriptor
EndFunc   ;==>_GetSecurityDescriptor


Func _MapGenericMask(ByRef $GenericMapping, ByRef $genericAccessRights)
    Local $aRet = DllCall("Advapi32.dll", "none", "MapGenericMask", "dword*", $genericAccessRights, "ptr", DllStructGetPtr($GenericMapping))
    $genericAccessRights = $aRet[1]
EndFunc   ;==>_MapGenericMask

Saludos

Link to comment
Share on other sites

But that's exactly what the OP tries to avoid!

Quote

without really write a file and check for errors?

 

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2022-02-19 - Version 1.6.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
OutlookEX (2021-11-16 - Version 1.7.0.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX_GUI (2021-04-13 - Version 1.4.0.0) - Download
Outlook Tools (2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
PowerPoint (2021-08-31 - Version 1.5.0.0) - Download - General Help & Support - Example Scripts - Wiki
Task Scheduler (NEW 2022-07-28 - Version 1.6.0.1) - Download - General Help & Support - Wiki

Standard UDFs:
Excel - Example Scripts - Wiki
Word - Wiki

Tutorials:
ADO - Wiki
WebDriver - Wiki

 

Link to comment
Share on other sites

Thanks Danyfirex, i'll study it and i'm sure in future will be useful also to others. It require admin because the folder you have choice or in any case?

Trong i need to check many directory...write file-delete file, write file-delete file and so on isn't be best choice for me or i'll be using simply FileOpen and check the return.

Edited by Terenz

Nothing is so strong as gentleness. Nothing is so gentle as real strength

 

Link to comment
Share on other sites

@Terenz,

30 minutes ago, Terenz said:

... i need to check many directory ...

the solutions you are offered here are more suitable for a script running at user level to check that it is allowed to write to a specific folder or file before actually doing so, to avoid errors. if you need a mass checkup operation, then perhaps a dedicated utility is due here? look at Sysinternals security utilities here, and more specifically at AccessEnum on that page - this utility traverses the directory tree and displays users permissions in a very convenient manner.

 

Signature - my forum contributions:

Spoiler

UDF:

LFN - support for long file names (over 260 characters)

InputImpose - impose valid characters in an input control

TimeConvert - convert UTC to/from local time and/or reformat the string representation

AMF - accept multiple files from Windows Explorer context menu

DateDuration -  literal description of the difference between given dates

Apps:

Touch - set the "modified" timestamp of a file to current time

Show For Files - tray menu to show/hide files extensions, hidden & system files, and selection checkboxes

SPDiff - Single-Pane Text Diff

 

Link to comment
Share on other sites

5 hours ago, Terenz said:

Thanks Danyfirex, i'll study it and i'm sure in future will be useful also to others. It require admin because the folder you have choice or in any case?

Trong i need to check many directory...write file-delete file, write file-delete file and so on isn't be best choice for me or i'll be using simply FileOpen and check the return.

Hello. #RequiereAdmin Is just for test that even if you run with admin you can't write in "C:\System Volume Information" But can in "C:\".  (All this if UAC is enable)

You can check removing #RequiereAdmin and will notice that you can't write in "C:\" (If UAC is enable).

 

Saludos

 

Link to comment
Share on other sites

  • 3 years later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...