VBScript FileExists fails consistantly - asp.net

We're trying to read some log files for our application but FileExists is failing in every case. So I simplified the problem with this test code:
Dim filespec, msg
filespec = Chr(34) & "C:\Windows\explorer.exe" & Chr(34)
'filespec = "C:\Windows\explorer.exe"
'filespec = Chr(34) & "C:" & Chr(34)
'filespec = "C:"
'filespec = "default.asp"
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
msg = filespec & " exists."
Else
msg = filespec & " doesn't exist."
End If
Response.Write(msg)
As you can see, we've tried testing with and without added Chr(32) (which is the double quote character). We're testing against the file C:\Windows\explorer.exe and the file C:\Windows\explorer.exe does exist on the computer hosting the asp files and the iis server. We even fail when simply checking to see if the C drive exist.
Additionally, it even fails if we try to see if the default.asp file exists and that file is in the same directory as our filetest.asp file.
Does anyone see why our FileExists is consistently failing? Thank you.

filespec = "C:\Windows\explorer.exe"
Without the additional quotes will work. To find a folder we need to use
fso.FolderExists
Instead of FileExists.
This still doesn't find the default.asp file in the same directory. But that problem is too far removed from our actual problem which is to look at log files on another drive. That problem is too far from this original question so I'll post that problem separately.

You may want to try to load the folder in to a folder object and loop through files in the folder object. Below is an example.
Set fso = CreateObject("Scripting.FileSystemObject")
FileToFind = "explorer.exe"
FolderToSearch = "C:\Windows\"
Set myFolder = fso.GetFolder(FolderToSearch)
For each myFile in myFolder.Files
If myFile.Name = FileToFind Then
Wscript.echo "Found " & myFolder.Path & "\" & myFile.Name
End If
Next

you do not need to insert additional quotes. removing your quotes will work just fine.
Dim filespec, msg
filespec = "C:\Windows\explorer.exe"
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
msg = filespec & " exists."
Else
msg = filespec & " doesn't exist."
End If
Response.Write(msg)
In the past, I have only noticed that you need to insert additional quotes when using the wshshell.run since a space might be interpreted as additional arguments to the filename.

It appears that our problem is not in the VBScript at all. The app is running inside an ApplicationPool in iis. The Identity property of that Application Pool is the dynamically created applicationPoolIdentity user. This is a user with no permissions. So essentially, the application is running as a user which does not have access to any other drives. Therefore, it cannot find any file on any network drive. We will have to create an additional identity with the proper rights and set our applicationPool identity to use that custom account.
I found instructions on how to set this identity account here: http://technet.microsoft.com/en-us/library/cc771170%28v=ws.10%29.aspx

Related

Server.MapPath changes file path when passed outside of Class

I abbreviated my code here and hope convey enough data to express the problem I am having. I am more than happy to elaborate as needed.
Background:
I have an asp site that has about 70 pages that open files from various locations.
In one scenario I do some file manipulation, like copy, rename, convert to PDF etc.
This is done my moving the file into the project and then eventually serving the file from a project folder.
Originally I created a class with a few functions.
I call the function from the web page and the class manipulates and then opens the file.
Dim ReturnValue As String = OpenMyFile.OpenQCBD(Doc_Id)
The function would manipulate the file and the open it (note the creation of the file path)
OpenTempFile(HttpContext.Current.Server.MapPath(fpath & "\") & FileName.ToLower, FileName)
Then opens it (contained in the class)
Public Sub OpenTempFile(strURL As String, FileName As String)
Dim req As WebClient = New WebClient()
Dim response As HttpResponse = HttpContext.Current.Response
response.Clear()
response.ClearContent()
response.ClearHeaders()
response.Buffer = True
response.AppendHeader("Content-Disposition", "attachment; filename=""" & FileName & """")
response.WriteFile(strURL)
response.Flush()
response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
This all worked great and passed the proper file path and opened the file (e.g. \\MyServer\Folder...) This was tested both locally and in production and worked as expected.
I had to make a change and pass the file path back to the asp page and then call the procedure to open the file from there.
Class the function from asp page (same)
Dim ReturnValue As String = OpenMyFile.OpenQCBD(Doc_Id)
Instead of opening the file return the file path
Result = HttpContext.Current.Server.MapPath(fpath & "\") & FileName.ToLower
And then open the file (call from asp page)
OpenMyFile.OpenTempFile(FilePath, Path.GetFileName(FilePath))
This works great running locally on my machine.
However when I run it from the production server the class function returns C:Folder/.. instead //server/folder/... like it did before.
Construction of the file path is the same in both scenarios.
OpenTempFile(HttpContext.Current.Server.MapPath(fpath & "\") & FileName.ToLower, FileName)
vs
Result = HttpContext.Current.Server.MapPath(fpath & "\") & FileName.ToLower
The only difference is passing it back to the asp page, this is where I receive the wrong path.
Again - works fine on my local machine
Any help or direction would be super helpful, thanks in advance.

Can't connect to mapped drive in GetFolder for FileSystemObject ASP Classic

I am trying to connect to R:\database\attendanceData\ a mapped drive to be used in the following code
sDir = "R:\database\attendanceData\"
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set obj_FolderBase = fso.GetFolder(sDir)
if obj_FolderBase.Files.Count = 0 then '=== Check if Attendance record data is in
response.write " No Attendance Data Found!"
response.End
end if
response.write "IT is working"
response.End
The file structure
But I get the following error
However if I move my files to C: drive, everything is working.
But it needs to be in a shared drive. Do I need to set some permission at R: or am I missing something, please help.

Overcome Permissions Errors When Traversing the File System

I am building a VBScript to search for and record the locations of files that have been copied out of a home directory (duplicates).
I currently have a script that recursively searches the C drive and records all file locations to a log file. (This is not elegant, but I am still working on a proof of concept.)
As I iterate through the file system, however, I find that there are a great many folders the script cannot even view- Appdata, Local Settings, My Videos, My Pictures, etc.
So of these are obviously inaccessible to the user, but the user has ownership over the folders in My Documents, so I cannot determine why my script cannot even read their contents. The user is a local administrator.
I have tried running the script with elevated permissions by adding this snippet to the beginning with no change in behavior:
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, WScript.ScriptFullName & " /elevate", "", "runas", 1
WScript.Quit
End If
This is a salient Function in the script, with the line that errors out notated (please let me know if another portion would be of aid):
' Get list of ALL files recursively and record them in a text file
Function getAllFilesRecursively (specifiedFolder, logLocation)
If (Right(specifiedFolder,7)<>"AppData") And _
(Right(specifiedFolder,16)<>"Application Data") And _
(Right(specifiedFolder,7)<>"Cookies") And _
(Right(specifiedFolder,14)<>"Local Settings") Then
' Get list of files in current folder
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(specifiedFolder.Path)
Set colFiles = objFolder.Files
'This function writes to a specified log file, using the specified method
writeToFile specifiedFolder, logLocationTemp, "Append"
' For each file, perform a task
For Each objFile in colFiles '(<<<<<<<<<<<<<<<<<<<< permissions error)
' Compose the full path to the file
fullPath = specifiedFolder & "\" & objFile.name
'Save the path to a text file (a newline is automatically added)
writeToFile fullPath, logLocation, "Append"
Next
' For each folder, Recurse
For Each Subfolder in specifiedFolder.SubFolders
getAllFilesRecursively Subfolder, logLocation
Next
End If
End Function
Is there any way for me to allow this script access to these folders? The computer is on a domain but I can make whatever modifications necessary (even policies).
The folders that are giving you errors probably aren't actual folders, but symbolic links to folders. They exist for compatibility reasons and have an ACE "everyone deny list folder, this folder only" on them to prevent people from browsing. Don't tamper with them. Make an exclusion list to prevent your script from trying to traverse them.
Set exclude = CreateObject("Scripting.Dictionary")
exclude.CompareMode = vbTextCompare
exclude.Add "Application Data", True
exclude.Add "Local Settings", True
...
Function getAllFilesRecursively (specifiedFolder, logLocation)
...
For Each Subfolder in specifiedFolder.SubFolders
If Not exclude.Exists(Subfolder.Name) Then
getAllFilesRecursively Subfolder, logLocation
End If
Next
End Function

The Microsoft Access database engine could not find the object test.13.csv

I am working classic ASP project. In this project there is option for users to upload CSV.
Now what is happening is, if I upload CSV file with more than one dot, for example test.13.csv then I get:
The Microsoft Access database engine could not find the object 'test.13.csv'. Make sure the object exists and that you spell its name and the path name correctly
But if I save the same file as test.csv, then it takes file properly.
So can anyone tell me how can I allow my code to accept more than one dot in csv file?
I am using following provider :
sFileDSN = "Provider=" & msdbProviderString() & ";Data Source=" & objFile.Folder & ";Extended Properties=""text;HDR=YES;IMEX=1;MaxScanRows=0;ImportMixedTypes=Text;"""
You can enclose your filename in single quotes like this:
sFileDSN = "Provider='" & msdbProviderString() & "';Data Source=" & objFile.Folder & ";Extended Properties=""text;HDR=YES;IMEX=1;MaxScanRows=0;ImportMixedTypes=Text;"""
Here is a reference, it doesn't specifically mention periods but does address other special characters:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms722656(v=vs.85).aspx

Using a variable from a VBScript in a ASP.Net website

I've been researching this for a majority of the day and can't find the answer. I am relatively new to stackoverflow. Is there a certain etiquette for asking a number of questions (I've asked three in the last few days)?
Anyways,
Here is the code in a codebehind file. It executes a script systeminfo.vbs, and that is working fine. But in the script I have some variables assigned.
Dim WshShell = CreateObject("WScript.Shell")
WshShell.Run("wscript.exe c:\systeminfo.vbs")
vbscript
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSettings = objWMIService.ExecQuery _
("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colSettings
dim osName
osName = objOperatingSystem.Name
Wscript.Echo "OS Name: " & objOperatingSystem.Name
dim osVer
osVer = objOperatingSystem.Version
Wscript.Echo "Version: " & objOperatingSystem.Version
Wscript.Echo "Service Pack: " & _
objOperatingSystem.ServicePackMajorVersion _
& "." & objOperatingSystem.ServicePackMinorVersion
Wscript.Echo "OS Name: " & objOperatingSystem.SizeStoredInPagingFiles
Next
I want to use osName and osVer and put the values into a label on the ASP side.
I understand that osName and osVer are simple examples, but I just need to figure out the concept of putting variables from a VBScript into ASP. My client has multiple VBScripts they use on a daily basis and I need to automate those scripts and produce a report saying if it failed or not.
Thank you for the help.
David,
As a person new to Stack Overflow myself, I was happy to find this very comprehensive FAQ for Stack Exchange sites. See the 3rd question "Is there a limit on how many questions I can ask?" for an answer to your first inquiry.
Regarding the heart of your question, I agree with #Ramhound that using a log file to exchange information between your WSH/VBScript script and your ASP.NET page is a feasible approach.
What you need is the Scripting.FileSystemObject. Here is a comprehensive WSH reference as a downloadable Windows help file.
Hint: as the download page advises at the bottom, to unblock the help page, 1) Right click on script56.chm, 2) Choose Properties, and 3) Click on "Unblock."
You'll find an intro to FileSystemObject under the heading "Script Runtime."
One more suggestion: since you'll be running this script via ASP.NET in a multi-user environment, you may find you'll need to create a log file per user or per page access. If that is the case, you'll need to generate a temporary file name for each log file to avoid name collisions with other log files. To generate your temporary file, see GetTempName in the WSH reference.

Resources