Use Scripting.FileSystemObject to create file in path that doesn't already exist

此生再无相见时 提交于 2020-01-05 09:03:13

问题


I'm trying to create a text file using the Scripting.FileSystemObject in JScript. I can't seem to figure out how to create the file if a directory in the file doesn't already exist. For example:

var fso = new ActiveXObject("Scripting.FileSystemObject");

// Getting a JScript runtime error of "Path not found"
fso.CreateTextFile("\\\\pathA\\pathB\\DirectoryDoesntExistButIWantItTo\\newfile.txt", true);

I've been looking all over but it seems like the documentation on this isn't neatly put in one place. For example, here are some MSDN articles which talk about this but leave out the details I'm looking for.

http://msdn.microsoft.com/en-us/library/aa711216(v=VS.71).aspx

http://msdn.microsoft.com/en-us/library/aa242706(v=VS.60).aspx

In other words, I'm trying my best to Google this and I'm not finding what I'm looking for. I don't think this makes a difference; but I'm writing this script within TestComplete 8; but for all intensive purposes you can assume I'm running it in a script tag within an html file on IE.


回答1:


If you are going to run your code in TestComplete, you can use its own aqFileSystem.CreateFolder and aqFile.Create methods. Here is an example:

createFile("\\\\pathA\\pathB\\DirectoryDoesntExistButIWantItTo\\newfile.txt");
...
function createFile(fileName)
{
  aqFileSystem.CreateFolder(aqFileSystem.GetFileFolder(fileName));
  aqFile.Create(fileName);
}



回答2:


I think that you need to manually create the folder if it doesn't exist. If you only need to worry about the immediate parent folder, you can use GetParentFolderName to help:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var path = "\\\\pathA\\pathB\\DirectoryDoesntExistButIWantItTo\\newfile.txt";
var folder = fso.GetParentFolderName(path);

if (!fso.FolderExists(folder))
{
    fso.CreateFolder(folder);
}

fso.CreateTextFile(path, true);


来源:https://stackoverflow.com/questions/8513213/use-scripting-filesystemobject-to-create-file-in-path-that-doesnt-already-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!