1

I am trying to open a file with read permissions

var namestart=fso.OpenTextFile("C:\\name.txt",1);
var name2=namestart.ReadAll();
namestart.Close();

But this file is not always filled with something, ReadAll gives an error when the file is empty because (of course) it cannot read what's in the file and returns an error. Is there any way I can catch this error?

var namestart=fso.OpenTextFile("C:\\naam.txt",1);
var name2="";
if(namestart.ReadAll() != ""){
    name2=namestart.ReadAll();
}
namestart.Close();

That doesn't work either as ReadAll returns an error.

Conceptual
  • 57
  • 2
  • 12

2 Answers2

3

You can use AtEndOfStream Property.

var namestart=fso.OpenTextFile("C:\\name.txt",1);
var name2 = namestart.AtEndOfStream ? "" : namestart.ReadAll();
namestart.Close();
Kul-Tigin
  • 16,728
  • 1
  • 35
  • 64
1

You can check the .Size of the (existing) file or use try/catch to deal with not existing (as in the code below) and zero-length files.

var oFS    = new ActiveXObject("Scripting.FileSystemObject");
var aFiles = ".\\25057783.js .\\empty.txt .\\nothere.nix".split(/ /);
for (var iFile in aFiles) {
    var sFile = aFiles[iFile];
    WScript.Echo("----", sFile)
    try {
      var oFile = oFS.GetFile(sFile);
      if (0 < oFile.Size) {
         var sContent = oFile.OpenAsTextStream().ReadAll();
         WScript.Echo("     got content")
      } else {
        WScript.Echo("     file is empty");
      }
    }
    catch(e) {
      WScript.Echo("     Bingo:", e.message);
    }
}

output:

cscript 25057783.js
---- .\25057783.js
     got content
---- .\empty.txt
     file is empty
---- .\nothere.nix
     Bingo: File not found
Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96