Question

I'm getting this really weird problem when I try to create a text file using javascripting and a hta file.

This is the code broken down to its basics:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>

alert("creating file");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("test.txt", true);
s.WriteLine("it works");
s.Close();
alert("file created");
</script>
</head>

<body>
</body>
</html>

This is in a hta file called "Untitled.hta" As long as I set the Open With > Choose Default Program to "Microsoft (R) HTML Application Host" and then open the hta file the text file gets created just fine.

But if I set Open With > Choose Default Program to "Notepad" and then Open With "Microsoft (R) HTML Application Host" the text file doesn't get created.

Does anyone know why this is happening? It normally wouldn't matter but if a client has hta files set to open as notepad by default then my hta file wont work as intended.

To complicate things further replace

var s = fso.CreateTextFile("test.txt", true);

with

var s = fso.CreateTextFile("TestFolder/test.txt", true);

and where the hta file is located create a folder called "TestFolder"

If you do the same thing as you did before, having it set to Notepad as default gives the Path not found error (but it works fine if the default is set to Microsoft (R) HTML Application Host)

Was it helpful?

Solution

That happens because you are using a relative path. Put this snippet before creating a FSO:

var shell = new ActiveXObject("WScript.Shell");
alert(shell.currentDirectory);

Probably your HTA alerts C:\Windows\System32 (depended on the used OS). This is the folder, where you can find test.txt. Also "Path not found" error is now explained...

To fix the issue, use absolute paths only, or set the current directory:

shell.currentDirectory = 'C:/Some_Path';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top