Jump to content

_FileInUse to check if file is in used or not (work on both local and network drive)


Recommended Posts

This is my first thread in Example, so please easy with me :)

I found a function by Rogue5099 to check if a file is in used or not, but it only working great when

checking a file in local drive. I make a little change so it can also report a correct "file in used" status

for files that on network.

I hope this script can benefit for every of us :)

$fFile = "c:\myscript.exe"

If _FileInUse($fFile) = 0 then
    Msgbox(64, "Info", $fFile & " is NOT in used")
Else
    Msgbox(64, "Info", $fFile & " is in used")
EndIf


;===============================================================================
;
; Function Name:    _FileInUse()
; Description:      Checks if file is in use
; Parameter(s):     $sFilename = File name
; Return Value(s):  1 - file in use (@error contains system error code)
;                   0 - file not in use or file not exists
; Create by:         Rogue5099
; Modified by:        michaelslamet
;
;===============================================================================

Func _FileInUse($sFilename)
    ;note: dword", 0x40000000, _  ---> jalan bagus jika $sFilename ada di hdd local, tapi jika $sFilename ada di network drive, gunakan dword", 0x80000000, _
    Local $aRet, $hFile
    If StringUpper(DriveGetType($sFilename)) = "NETWORK" Then
        $aRet = DllCall("Kernel32.dll", "hwnd", "CreateFile", _
                                    "str", $sFilename, _ ;lpFileName
                                    "dword", 0x80000000, _ ;dwDesiredAccess = GENERIC_READ
                                    "dword", 0x00000004, _ ;dwShareMode = DO NOT SHARE
                                    "dword", 0, _ ;lpSecurityAttributes = NULL
                                    "dword", 3, _ ;dwCreationDisposition = OPEN_EXISTING
                                    "dword", 128, _ ;dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL
                                    "hwnd", 0) ;hTemplateFile = NULL
    Else
            $aRet = DllCall("Kernel32.dll", "hwnd", "CreateFile", _
                                    "str", $sFilename, _ ;lpFileName
                                    "dword", 0x40000000, _ ;dwDesiredAccess = GENERIC_WRITE
                                    "dword", 0x00000004, _ ;dwShareMode = DO NOT SHARE
                                    "dword", 0, _ ;lpSecurityAttributes = NULL
                                    "dword", 3, _ ;dwCreationDisposition = OPEN_EXISTING
                                    "dword", 128, _ ;dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL
                                    "hwnd", 0) ;hTemplateFile = NULL
    EndIf

    If NOT FileExists($sFilename) Then
        Return 0
    Else
        $hFile = $aRet[0]
        If $hFile = -1 Then ;INVALID_HANDLE_VALUE = -1
            $aRet = DllCall("Kernel32.dll", "int", "GetLastError")
            SetError($aRet[0])
            Return 1
        Else
            ;close file handle
            DllCall("Kernel32.dll", "int", "CloseHandle", "hwnd", $hFile)
            Return 0
        EndIf
    EndIf
EndFunc
Link to comment
Share on other sites

I might use this for something... :P

Not sure if useful or not,

SetError($aRet[0])
Return 1

; Could be:
Return SetError($aRet[0], 0, 1)
Edited by DatMCEyeBall

"Just be fred, all we gotta do, just be fred."  -Vocaliod

"That is a Hadouken. A KAMEHAMEHA would have taken him 13 days and 54 episodes to form." - Roden Hoxha

@tabhooked

Clock made of cursors ♣ Desktop Widgets ♣ Water Simulation

Link to comment
Share on other sites

You don't really need StringUpper as = is case-insensitive anyway. If you were using == then OK it would be valid, but it's not in this case.

For the purposes of learning the next generation of AutoIt, how does this work for you? You will need v3.3.9.6 and above. 

#include <APIErrorsConstants.au3>
#include <Constants.au3>
#include <WinAPI.au3>

; Works with v3.3.9.6+

Local $hFileOpen = FileOpen(@ScriptFullPath, $FO_READ)
MsgBox($MB_SYSTEMMODAL, '', 'Is the file in use: ' & _FileIsUsed(@ScriptFullPath) & @CRLF)
FileClose($hFileOpen)

Func _FileIsUsed($sFilePath) ; By Nessie. Modified by guinness.
    Local Const $hFileOpen = _WinAPI_CreateFile($sFilePath, $CREATE_ALWAYS, (DriveGetType($sFilePath)) = 'NETWORK' ? $FILE_SHARE_READ : $FILE_SHARE_WRITE)
    Local $fReturn = True
    If $hFileOpen Then
        _WinAPI_CloseHandle($hFileOpen)
        $fReturn = False
    EndIf

    If $fReturn Then
        $fReturn = _WinAPI_GetLastError() = $ERROR_SHARING_VIOLATION
    EndIf
    Return $fReturn
EndFunc   ;==>_FileIsUsed

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

  • 1 year later...

is there some process dependency that can cause the code not to work (I keep receiving a false return)
anyone got an idea what can cause this not to work, as I think this used to work before

for now I have tried a system reboot to avoid any system instabilities

i have tried locked and none locked files and got the same return.
 

Func _FileIsUsed($sFilePath) ; By Nessie. Modified by guinness.
    Local Const $hFileOpen = _WinAPI_CreateFile($sFilePath, $CREATE_ALWAYS, (DriveGetType($sFilePath)) = 'NETWORK' ? $FILE_SHARE_READ : $FILE_SHARE_WRITE)
    Local $fReturn = True

;~     $hFileOpen is allways = 0

    If $hFileOpen Then
        _WinAPI_CloseHandle($hFileOpen)
        $fReturn = False
    EndIf

;~      $fReturn is allways = True

    If $fReturn Then
        $fReturn = _WinAPI_GetLastError() = $ERROR_SHARING_VIOLATION
    EndIf

;~     fReturn = is allways False
    
EndFunc   ;==>_FileIsUsed

 

Edited by Deye
Link to comment
Share on other sites

I've tested

Local $hFileOpen = FileOpen(@ScriptFullPath, $FO_READ)
MsgBox($MB_SYSTEMMODAL, '', 'Is the file in use: ' & _FileInUse(@ScriptFullPath) & @CRLF)
FileClose($hFileOpen)

and shows to work just fine. Old DLL call and new_WinAPI_ , share a bit more of your code, maybe we can help better

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Link to comment
Share on other sites

Thanks for the reply

I have used the same code to test on a nother computer with sucsess

but wondering what is causing it fail here , I guess it needs some WinAPI error checking workaround 
to determine if this will run correctly at run-time 
so other steps in the script can be taken if this yields nothing

Link to comment
Share on other sites

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...