Search code examples
automationlocalizationautohotkey

AHK: How to store a selected file in a variable to execute an script using FileSelectFile function after selected in Window/File explorer?


Apologies, I am quite new with AHK.

Context: I am trying to build a small program (eventually with UI) which will clean data in .XLF files in order to be processed properly by a CAT tool interpreter (import into it).

By "clean" I mean to find HTML attributes and replace them with their respective Char Entities. This as a single script; writing the name of the file or path inside the script is working perfectly.

Problem: I would like to run my .ahk/.exe allowing the user to open the file manager/explorer and select the file that needs to be processed by the script (find/replace html attributes with char entities) selecting the file is not working. Nothing is populated (the final file/result is empty) I'm trying to sort out this with FileSelectFile function and store the output var value (selecting the file) in the first instruction "fileread, selectedfile".

But it's not working! If I don't do this and I only provide in the default directory "A_ScriptDir" an specific file name .xf -> this works fine.

This is my code so far w/comments:


SetWorkingDir, %A_ScriptDir%

FileEncoding, UTF-8
;NoEnv


;Open Window File Manager/Explorer and select a file .xlf file

FileSelectFile, SelectedFile, 8, , Open a file, , ,(*.xlf)



;---  > HTML attribute '&' must be replaced by its char entity first/overall otherwise this instruction will overwrite the amp entities from the rest of char entities corrupting the file;


;"SelectedFile" can be any filename such as "example.xlf" but this is not my scope

fileread, text, SelectedFile  ;previously "text.xlf" with random html content to do tests

replace := "&"
newtext := strreplace(text, "&", replace, all)

sleep, 200

filedelete, newtest.xlf 
fileappend, %newtext%, newtest.xlf

;--------------------------------- <b>
;here "fileread" must read the final appended file as solution to use "streplace" function multiple times (replace more than one desired string) running the script at the same time. (due to my lack of exp. with loop function)

fileread, text, newtest.xlf 

replace := "&gt;b&lt;"
newtext := strreplace(text, "<b>", replace, all)

filedelete, newtest.xlf 
fileappend, %newtext%, newtest.xlf


I've been thinking that other solution can be:

I am still new to understand apply Drag and Drop GUI but I am unsure how to modify my code in order to drag/drop a file onto the ahk.exe

Thanks for your time reading this! any tip and/or help would be super appreciated :)


Solution

  • The FileRead command expects text, not an input variable. So if you add % around SelectedFile like this, it should work:

    FileRead, text, %SelectedFile%
    

    If that doesn't work, it means the file does not exist or an error occurred. In that, you'll want to look at FileRead's error handling section.