CreateTextFile not working when hta is set to open

2020-03-27 01:51发布

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)

1条回答
啃猪蹄的小仙女
2楼-- · 2020-03-27 02:35

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';
查看更多
登录 后发表回答