Web server ignores savepath and saves to wwwroot, while localhost works perfectly - asp.net

When I try to use FileUpload1.SaveAs(savePath), it works very strangely.
When using localhost, it uses the savePath perfectly. I have used a variety of paths and syntaxes to confirm this. However, when I publish this to my website, and use the upload feature there, it saves the file to the wwwroot folder, and nowhere else.
In fact, no matter what the path is specified, it ALWAYS saves to wwwroot, even when I tell it otherwise.
Sub SaveFile(ByVal file As HttpPostedFile)
' Specify the path to save the uploaded file to.
Dim savePath As String = Server.MapPath("\uploads\")
' Get the name of the file to upload.
Dim fileName As String = FileUpload1.FileName
' Create the path and file name to check for duplicates.
Dim pathToCheck As String = savePath + fileName
' Create a temporary file name to use for checking duplicates.
Dim tempfileName As String
' Check to see if a file already exists with the
' same name as the file to upload.
If (System.IO.File.Exists(pathToCheck)) Then
Dim counter As Integer = 2
While (System.IO.File.Exists(pathToCheck))
' If a file with this name already exists,
' prefix the filename with a number.
tempfileName = counter.ToString() + fileName
pathToCheck = savePath + tempfileName
counter = counter + 1
End While
fileName = tempfileName
' Notify the user that the file name was changed.
UploadStatusLabel.Text = "A file with the same name already exists." + "<br />" + _
"Your file was saved as " + fileName
Else
' Notify the user that the file was saved successfully.
UploadStatusLabel.Text = "Your file was uploaded successfully."
End If
' Append the name of the file to upload to the path.
savePath += fileName
' Call the SaveAs method to save the uploaded
' file to the specified directory.
FileUpload1.SaveAs(savePath)
End Sub
Once I get through this problem, I would like the path to be going to a virtual directory, which I have already created through IIS, but because of this problem, I can not test it.

would it work like,
Dim savePath As String = Server.MapPath("~/uploads/")
just check by changing direction of slash to /

I figured out that the changes to the upload process were not being fully changed unless I deleted the files in root, and republished them. Publishing the changes without deleting the initial files did not fix the upload process. Still somewhat mysterious, but at least I found a hard fix to the problem. Likely a change is made in web.config, or another file, which causes the changes to not fully occur unless a fresh start was made.

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.

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

Display image using string builder in ASP.Net

my need is to display an image in a web page using string builder. i know through this snippet sb.Append("<img src=\"bla.jpg\" />"); i can display an image. Here my problem is that the image path is dynamically generated and is in a string variable.
following is the code i tried:
Dim table_builder As New StringBuilder
table_builder.Append("<table width=100%>")
Dim filePath As String = Server.MapPath("../attachments/") & fileName
// file name is the name of the file fetching from the database
table_builder.Append("<tr>")
table_builder.Append("<td>")
table_builder.Append("<img src='" + filePath + "'/>")
table_builder.Append("</td>")
table_builder.Append("</tr>")
But it does not show the image through executing the code
table_builder.Append("</table>")
attach.innerHTML = table_builder.ToString()
Server.MapPath("../attachments/") will map the physical path, that's why the image is not showing. so you can edit your code as:
table_builder.Append("<table width=100%>")
table_builder.Append("<tr>")
table_builder.Append("<td>")
table_builder.Append("<img src='" + "../attachments/" & fileName + "'/>")
table_builder.Append("</td>")
table_builder.Append("</tr>")
table_builder.Append("</table>")
attach.innerHTML = table_builder.ToString()
For your reference ,The Answer by splattne says that :
Server.MapPath specifies the relative or virtual path to map to a physical directory.
Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
Server.MapPath("..") returns the parent directory
Server.MapPath("~") returns the physical path to the root of the application
Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
Server.MapPath will return the PHYSICAL path of the file on the server. You certainly don't want that as the file will not be accessible from the client side.
You should use relative path
like Dim filePath As String = ("/attachments/") & fileName
with that the file should be accessible from client as
http://domainname.com/attachments/filename
also be careful while using ../ in your paths. You might end up one level lower to your root path and it might not be accessible from client side
Typically ~ can be used to always start the paths from site root

VBScript FileExists fails consistantly

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

get the servername + foldername (without script name)

how to get the servername + foldername without containing the script name?
string filePath = Request.QueryString.Get("filepath");
string serverPath = Request.ServerVariables["SERVER_NAME"] + "/";
string fullUrl = "http://" + serverPath + filePath;
Response.Write(fullUrl);
the above code is missing folder name.
This page demonstrates how the parts of a HttpRequest break down. You could take the Request.FilePath and remove the final segment like so:
string directory = Request.FilePath.Remove(Request.FilePath.LastIndexOf('/'));
You can't quite do that, because HTTP is "blind" to what's a folder and what's a file.
You are probably familiar with URLs such as http://www.acme.com/products/view.asp but a completely valid URL could also be http://www.acme.com/products/view , so you can't differentiate a folder and a file name.
What you CAN do, provided that:
you know your application and know that it only runs files (as opposed to some routing mechanism that runs some logical piece of code, such as in MVC for example)
each file contains an extension
is to parse the path string on your own and look for file.ext pattern in the end of the path.

Resources