What's the correct way to specify file path in VBscript? - asp-classic

New to VBscript and spending way too much time trying to find the right way to open a file for reading. Whatever I've tried I always get "Path not found" error.
This is the real path to my files:
D:\InetPub\vhosts\lamardesigngroup.com\httpdocs\
The file that I am trying to run is:
D:\InetPub\vhosts\lamardesigngroup.com\httpdocs\ifp\files.asp
and I want to read this file:
D:\InetPub\vhosts\lamardesigngroup.com\httpdocs\ifp\css\style.css
Here is the code:
Dim objFSO, strTextFile, strData, strLine, arrLines
CONST ForReading = 1
'name of the text file
strTextFile = "//css/style.css"
'Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Open the text file - strData now contains the whole file
strData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll
'Split the text file into lines
arrLines = Split(strData,vbCrLf)
'Step through the lines
For Each strLine in arrLines
response.write(strLine & "<br>")
Next
'Cleanup
Set objFSO = Nothing
and I get "12|800a004c|Path_not_found 80"
I've also tried
strTextFile = "D:\InetPub\vhosts\lamardesigngroup.com\httpdocs\ifp\css\style.css"
' and
strTextFile = "\\css\style.css"
strTextFile = "css\style.css"
strTextFile = "css/style.css"
' and many other combinations
I'm obviously lost...

Morning Harley,
Give this a try:
strTextFile = server.MapPath("css/style.css")
It should result in recognizing your specific server location. I ran into this problem trying to get some vbscript file upload code to work. It should start from the folder your page is working in and go from there.

Related

HttpPostedFile and SaveAs not saving a part of the path

I'm trying to save a file that is uploaded using an HttpPostedFile control.
The main issue I'm running into, is that it won't create a new folder for the file.
In the code below, "file" is an HttpPostedFile.
So I have my base path that I define like this:
Dim basePath = "D:\\game\\world\\map\\MediaFiles\\"
Then I get the file name like this:
Dim fileName = Path.GetFileName(file.FileName)
Now I want to create a new path like this using the gameId (guid):
Dim newFolderAndFile As String = gameId + fileName
And then combine the path with the base path and save:
Dim saveAsPath = Path.Combine(basePath, newFolderAndFile)
file.SaveAs(saveAsPath)
But when I try that, I always get an error like this:
System.IO.DirectoryNotFoundException: Could not find a part of the
path
'D:\game\world\map\MediaFiles\05a10e9c-e8a9-49ed-ad4f-34b6b4650ef3\5.jpg'
So it looks like the saveAsPath is being constructed correctly, however SaveAs isn't saving it.
How can I get SaveAs to create the path and file?
Thanks!
As the_lotus explained, you need to create the directory first before saving the file
Dim basePath = "D:\game\world\map\MediaFiles\"
Dim fileName = Path.GetFileName(file.FileName)
' make new folder
system.io.direcotry.createdirectory(basepath & gameid)
Dim saveAsPath = (basePath & gameid & "\" & filename)
file.SaveAs(saveAsPath)
I'm not sure about the double slashes, I think that's not needed...

Asp.net: Excel file uploading does not finish but gives no error message

I'm having a rather weird problem trying to upload an Excel file and storing it in a SQL server table in an ASP.net App.
The file is not too big: about 2.5 or 3 Mb.
The problem is that the upload gets "interrupted" after loading some rows, appearently without causing any specific error, since the load process finishes by showing a success message that I'm sending to the client:
"The process finished successfuly: XXX rows were uploaded from the
file".
The problem is that the XXX rows are not all the rows from the file. Depending on how much information there is in each column of the Excel file, the process is only uploading, for instance, 15500 rows from a total of 25000 that the file has. (If there's less information in the Excel file, it can upload, lets say 20000 of the 25000 rows that it may have)... the fact is that the file is not being "completely" uploaded.
I already tried increasing the "httprequest-maxRequestLength" value in the web.config, even though the file is not bigger than the default 4Mb file upload that ASP.net has.
The code (vb.net) that I'm using upload and read the file is, basically, this:
Dim connection As DbConnection = Nothing
Dim Command As DbCommand = Nothing
Dim ConexionStringExcel As String
Dim dr As DbDataReader
Dim mensajeError as String = ""
Dim ncAdic as Integer = 0
Dim nReg as Integer = 0
'String connection for Excel 2007: for now, I'm not allowing other Excel versions
ConexionStringExcel = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source = " & sNombreArch & ";" & _
"Extended Properties=Excel 12.0 Xml;"
'sNombreArch is the full name of the uploaded file
connection = New OleDb.OleDbConnection(ConexionStringExcel)
Command = connection.CreateCommand()
Command.CommandText = "SELECT * FROM [" + nomHojaArch + "$]"
'---
'lblMensaje is a Label object in the aspx page:
'---
lblMensaje.Visible = False
Try
'Open the Excel file
connection.Open()
'Read file content
dr = Command.ExecuteReader()
While dr.Read
Try
'Two first columns of the file are mandatory in my case...
If Not IsDBNull(dr(0)) And Not IsDBNull(dr(1)) Then
'---
'dsTempCargue is a SqlDataSource object in the aspx page
'---
dsTempCargue.InsertParameters.Item("idReg").DefaultValue = dr(0)
dsTempCargue.InsertParameters.Item("nombre").DefaultValue = dr(1)
For ncAdic = 2 To 10
If Not IsDBNull(dr(ncAdic)) Then
dsTempCargue.InsertParameters.Item(ncAdic).DefaultValue = dr(ncAdic)
Else
dsTempCargue.InsertParameters.Item(ncAdic).DefaultValue = DBNull.ToString
End if
Next
dsTempCargue.Insert()
nReg = nReg + 1
Else
mensajeError = "Column A and B of the File cannot be empty"
Exit While
End If
Catch exRead As Exception
mensajeError = "Error reading the file or saving its content: " & exRead.Message
Exit While
End Try
End While
'If there was no error, show success message
If String.IsNullOrEmpty(mensajeError) Then
mensajeError = "The process finished successfuly. " & nReg.ToString() & " rows were uploaded from the file"
End IF
Catch ex As Exception
mensajeError = "Error uploading the file: " & ex.Message
End Try
lblMensaje.Text = mensajeError
lblMensaje.Visible = True
Why do you think this uploading process is failing to read the entire file???... Any advice will be appreciated.
Thanks a lot,
Diego
For the tables that you are storing the rows in, what datatype are the various columns? Perhaps the content of one of the cells is incompatible with the column datatype. Do you have any way of checking?
Even though I'm really not sure about what could have been the cause of the error, I finally managed to get it working by changing my code to use a Third-party library that I found and that had some good comments, which is available here:
http://exceldatareader.codeplex.com/
I'm not really sure about what the original problem was and why using this library solved the issue, but It worked. (Perhaps when I have some time I'll try to find more info about this problem I had)
Thanks Patrick for your comments and all for the interest

Non-printable characters in file names break my recursive file listing VB Script

I created a VB script to recursively list all of its file and subfolder files. The script begins fine but eventually crashes in any folder containing a file with a non-printable character/s in their filenames, i.e. I see little squares when I browse the folder in Explorer. I'm not sure how to change my below error handling to continue when it finds a file with such characters.
Any advice or solutions would be appreciated. Thank you.
Set objFSO = CreateObject("Scripting.FileSystemObject")
strFolder = "C:\Input\"
Set objFolder = objFSO.GetFolder(strFolder)
Set NewFile = objFSO.CreateTextFile("C:\Output\" & objFolder.Name & " FileList.txt", True)
Set colFiles = objFolder.Files
On Error Resume Next
For Each objFile In colFiles
NewFile.WriteLine(objFile.Path)
If Err Then
Err.Clear
End If
Next
ShowSubFolders(objFolder)
Sub ShowSubFolders(objFolder)
Set colFolders = objFolder.SubFolders
For Each objSubFolder In colFolders
Set colFiles = objSubFolder.Files
For Each objFile In colFiles
NewFile.WriteLine(objFile.Path)
If Err Then
Err.Clear
End If
Next
ShowSubFolders(objSubFolder)
Next
End Sub
NewFile.Close
Create the output text file as unicode so it can handle "non printable" characters. Third parameter of CreateTextFile.
Set NewFile = objFSO.CreateTextFile(" ... ", True, True)
EDITED
If you can not work with unicode files, then file/folder names should be converted from unicode to ansi before writing to output file. This will do the conversion
Function Unicode2Ansi( text )
Unicode2Ansi = text
With (WScript.CreateObject("ADODB.Stream"))
' Put data into stream
.Type = 2 '( adTypeText )
.Charset = "x-ansi"
.Open
.WriteText text
'Retrieve data from stream
.Position = 0
Unicode2Ansi = .ReadText
.Close
End With
End Function
And adapt code to call it NewFile.WriteLine Unicode2Ansi(objFile.Path)

VBScript runtime error '800a0034' - Bad file name or number - When trying to write to server side text file

I'm trying to simply write to a text file for later use data collected from input elements on various pages. Admittedly I am likely missing the obvious, but of the variations I have tried and even some of the sample code I have found in many examples I always get the same error.
Code:
<%
Dim currentDirectoryPath, outFile, objFSO, objTextStream
Const fsoForWriting = 2
'Get and assign current directory path
currentDirectoryPath = Server.MapPath(".")
'Assign file name to be used
outFile = "\accdata.txt\"
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'Open the text file
Set objTextStream = objFSO.OpenTextFile(currentDirectoryPath & outFile, fsoForWriting, True)
'Write new line to text file
objTextStream.WriteLine "output this as one line of text"
'Close the file and clean up
objTextStream.Close
Set objTextStream = Nothing
Set objFSO = Nothing
%>
Result:
Microsoft VBScript runtime error '800a0034'
Bad file name or number
/asp/accounting/datacollect.asp, line 23
(Line 23 of the code is:)
Set objTextStream = objFSO.OpenTextFile(currentDirectoryPath & outFile, fsoForWriting, True)
This is far from being my first language and thus I don't posses a heap load of experience with it so any help or suggestions will be very much appreciated.

Save filenames in arabic using classic asp

Hey guys i am creating a runtime jnlp file for download and in that i got stuck up with the filename since it has arabic or other languages some time as the filename takes from username... when creating with that i get the file name as "اخطاء البرنامج.jnlp"
my code for creating file
Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile(Server.MapPath(id & "_" & user & ".jnlp"), true)
f.write(JNLPFile)
f.close
Set f = nothing
Set fs = nothing
where "user" in the CreateTextFile is the name given by the user which may sometimes contains unicode characters or other language characters...
any solutions for this problem....?
Well, FileSystemObject does not natively support UTF8.
What you should do instead of using File System Object and CreateTextFile to build a new text file is to use ADODB Stream object.
Following is an example of a VBScript procedure that would take your path as strPath and the content of the file as strOut.
Sub Generate_File(strPath,strOut)
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open
objStream.Position = 0
objStream.Charset = "UTF-8"
objStream.WriteText strOut
objStream.SaveToFile server.mappath(strPath),2
objStream.Close
End Sub

Resources