问题
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