Jump to content

FileOpen detect already opened file


Recommended Posts

Hi Folks,

I have a small GUI application that writes to a text file. This is basically the part of the script:

$fh = FileOpen("Test.txt", 9) ;Append at the end of the File and create the dir structure if it doesn't exist
FilewriteLine($fh, "Bli bla blubb...") ;Write 1 - many lines to the file
FileClose($fh)

So ... sometimes while that application is running, there is another file that does something like this:

$fh = FileOpen("Test.txt", 2) ;Open file, erase the contents
FileClose($fh)

Okay, so basically that is bad, because it results in the first script writing several "NULL"s to the file, so if I try to read that file with another script and _FileReadToArray() it basically exits with RC 2 (Unable to split the file).

So the question is: Can I detect that the first file is already opened by an application?

Maybe I need to mention that the files is stored on a network drive.

Any comments are welcome.

Regards,Hannes[spoiler]If you can't convince them, confuse them![/spoiler]
Link to comment
Share on other sites

Look at LockFile in my signature.

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

Try this:

#Include <WinAPI.au3>

ConsoleWrite(_FileIsUses(@ScriptDir & '\My.pdf') & @CR)

Func _FileIsUses($sFile)

    Local $hFile = _WinAPI_CreateFile($sFile, 2, 2, 0)

    If $hFile Then
        _WinAPI_CloseHandle($hFile)
        Return 0
    EndIf

    Local $Error = _WinAPI_GetLastError()

    Switch $Error
        Case 32 ; ERROR_SHARING_VIOLATION
            Return 1
        Case Else
            Return SetError($Error, 0, 0)
    EndSwitch
EndFunc   ;==>_FileIsUses

My UDF: NetInfo UDF Play with your network, check your download/upload speed and much more! YTAPI Easy to use YouTube API, now you can easy retrive all needed info from a video. NavInfo Check if a specific browser is installed and retrive other usefull information. YWeather Easy to use Yahoo Weather API, now you can easily retrive details about the weather in a specific region. No-IP UDF Easily update your no-ip hostname(s).

My Script: Wallpaper Changer Change you wallpaper dinamically, you can also download your wallpaper from your website and share it with all!   My Snippet: _ImageSaveToBMPConvert an image to bmp format. _SciteGOTO Open a file in SciTE at specific fileline. _FileToHex Show the hex code of a specified file

Link to comment
Share on other sites

You're welcome.

Nice function Nessie. Using Constants.

#include <WinAPI.au3>

Local $hFileOpen = FileOpen(@ScriptFullPath, $FO_READ)
ConsoleWrite(_FileIsUses(@ScriptFullPath) & @CRLF)
FileClose($hFileOpen)

Func _FileIsUses($sFilePath) ; By Nessie. Modified by guinness.
    Local Const $hFileOpen = _WinAPI_CreateFile($sFilePath, $CREATE_ALWAYS, $FILE_SHARE_WRITE)
    If $hFileOpen Then
        _WinAPI_CloseHandle($hFileOpen)
         Return False
    EndIf

    Local $fReturn = False
    If _WinAPI_GetLastError() = 32 Then $fReturn = True
    Return $fReturn
EndFunc   ;==>_FileIsUses

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

You're welcome.

Nice function Nessie. Using Constants.

#include <WinAPI.au3>

Local $hFileOpen = FileOpen(@ScriptFullPath, $FO_READ)
ConsoleWrite(_FileIsUses(@ScriptFullPath) & @CRLF)
FileClose($hFileOpen)

Func _FileIsUses($sFilePath) ; By Nessie. Modified by guinness.
    Local Const $hFileOpen = _WinAPI_CreateFile($sFilePath, $CREATE_ALWAYS, $FILE_SHARE_WRITE)
    If $hFileOpen Then
        _WinAPI_CloseHandle($hFileOpen)
         Return False
    EndIf

    Local $fReturn = False
    If _WinAPI_GetLastError() = 32 Then $fReturn = True
    Return $fReturn
EndFunc   ;==>_FileIsUses

Thanks for the compliment, but this isn't a function of mine.

I have this snippet in my snippet folder, but unfortunatly i don't know the author ;)

Edit:

The author seems to be Yashied and is here.

Edited by Nessie

My UDF: NetInfo UDF Play with your network, check your download/upload speed and much more! YTAPI Easy to use YouTube API, now you can easy retrive all needed info from a video. NavInfo Check if a specific browser is installed and retrive other usefull information. YWeather Easy to use Yahoo Weather API, now you can easily retrive details about the weather in a specific region. No-IP UDF Easily update your no-ip hostname(s).

My Script: Wallpaper Changer Change you wallpaper dinamically, you can also download your wallpaper from your website and share it with all!   My Snippet: _ImageSaveToBMPConvert an image to bmp format. _SciteGOTO Open a file in SciTE at specific fileline. _FileToHex Show the hex code of a specified file

Link to comment
Share on other sites

  • 1 year later...

For me doesn't work on network files.

If I open a file on the network from one PC and then start AutoIt from my PC .. when he checks if the file is open returns False! 

File opened on the network DiskstationVirtualCommercialeMarketplaceEsportazioniperAUTOITXLS-MetaclassiV3.xls. 

If opened from another PC:

Local Const $hFileOpen = _WinAPI_CreateFile($sFilePath, $CREATE_ALWAYS, $FILE_SHARE_WRITE) returns 0

Then $fReturn = False

If not opened from another PC

Local Const $hFileOpen = _WinAPI_CreateFile($sFilePath, $CREATE_ALWAYS, $FILE_SHARE_WRITE) returns <HWnd>0x000001FC 

then tries to close the handle and returns "False"

Do you have any suggestion?

Link to comment
Share on other sites

I know running 'net file' on the server housing the file will return if the file is opened by an outside computer.

It's the same as viewing 'Open file shares' through Server Management.

I'm not certain of anyone creating a wrapping function for that.  Best I could suggest is to use psexec to execute it on the server.  But that requires you have the rights to do so.

IEbyXPATH-Grab IE DOM objects by XPATH IEscriptRecord-Makings of an IE script recorder ExcelFromXML-Create Excel docs without excel installed GetAllWindowControls-Output all control data on a given window.
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

×
×
  • Create New...