Image.FromFile "File Not Found" when File is there - asp.net

I have a file stored in a directory within my site. When I attempt to access the file using image.fromfile, an exception is thrown saying that the file is not there. However, when I access the exact same file using the exact same path but loading it into an image control, the image loads flawlessly verifying that it is there.
The code that throws the file not found exception is:
Private Sub btnCombine_Click(sender As Object, e As EventArgs) Handles btnCombine.Click
Dim BMCanvas As Bitmap 'the "canvas" to draw on
Dim BackgroundTemplate As Image 'the background image
Dim img1Overlay As Bitmap 'the character image
BackgroundTemplate = Image.FromFile("~/Account/Images/Blue 1-02.jpg") 'Template Background Image
img1Overlay = Image.FromStream(FileUpload1.FileContent) 'First overlay image
BMCanvas = New Bitmap(500, 647) 'new canvas
Using g As Graphics = Graphics.FromImage(BMCanvas)
g.DrawImage(BackgroundTemplate, 0, 0, 500, 647) 'Fill the convas with the background image
g.DrawImage(img1Overlay, 50, 50, 100, 100) 'Insert the overlay image onto the background image
End Using
'Setup a path to the destination for the composite image
Dim folderPath As String = Server.MapPath("~/OutFiles/")
'Create a directory to store the composite image if it does not already exist.
If Not Directory.Exists(folderPath) Then
'If Directory (Folder) does not exists Create it.
Directory.CreateDirectory(folderPath)
End If
'Temporarily save the file as jpeg.
BMCanvas.Save(folderPath & "Temp1.jpg", Imaging.ImageFormat.Jpeg)
'View the resulting composite image in image control.
Image1.ImageUrl = folderPath & "Temp1.jpg"
BMCanvas.Dispose()
End Sub
And the code that verifies that the image is in-fact in the directory and successfully displays the image is:
Private Sub cboRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboRole.SelectedIndexChanged
If cboRole.SelectedIndex = 1 Then
Image1.ImageUrl = "~/Account/Images/Blue 1-02.jpg"
End If
End Sub
I cannot figure out why one way works and the other way does not.
I have also tried the following code without success:
'Another way to read the image files
Image = File.ReadAllBytes(Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "~/Account/Images/Blue 1-02.jpg")))

OK, the answer to second part of your question (the "Why it's working with ImageUrl?") is located in documentation
Quote:
Use the ImageUrl property to specify the URL of an image to display in
the Image control. You can use a relative or an absolute URL. A
relative URL relates the location of the image to the location of the
Web page without specifying a complete path on the server. The path is
relative to the location of the Web page. This makes it easier to move
the entire site to another directory on the server without updating
the code. An absolute URL provides the complete path, so moving the
site to another directory requires that you update the code.
It (the Image control) already has embedded feature of "Mapping" the path relatively to your web page folder.
When using path from within your code, without controls, like in Image.FromFile, you need to make sure path is correctly mapped, by using Server.MapPath
As you already did in your code for Directory creation.

You cannot have an Image from a relative url.
To get your Image as an System.Drawing.Image you need to get them from a physical path like this (in your case)
Dim image As System.Drawing.Image = System.Drawing.Image.FromFile(HttpContext.Current.Request.PhysicalApplicationPath & "\Account\Images\Blue 1-02.jpg") 'Server.MapPath("~/Account/Images/Blue 1-02.jpg"))

Related

search folder through directory ASP VB.NET

Is there a way to search folder name(whether its root folder or subfolder and with files inside) through web vb.net? I searched all over the internet and haven't found single help. this is what i've done so far. but this is in windows forms.
I am looking for web forms. thank you
Protected Sub search_Click(sender As Object, e As EventArgs) Handles Search.Click
Dim MainFldr = "d:\shared\"
Dim SKfiles() As System.IO.FileInfo
Dim FldrInfo As New System.IO.DirectoryInfo(MainFldr)
Dim flpth As String
flpth = ""
ListBox2.Items.Clear()
SKfiles = FldrInfo.GetFiles("*" & txtfolder.Text & "*.*", IO.SearchOption.AllDirectories)
For Each MySearchfile In SKfiles
flpth = ""
flpth = MySearchfile.DirectoryName + "\" + MySearchfile.Name
ListBox2.Items.Add(flpth)
Application.DoEvents()
Next
End Sub
Well, it turns out you can do the same in web land.
However, one huge "issue" to remember?
For any web page url, web page link, web page document reference? You will use the web site URL for that file in question.
So, say you have the web site (root) and then a folder called Images.
images\cat.jpg
So, the path name for the WEB SITE MARK up will be:
"~/images/cat.jpg
however, WHEN you run code behind? (your vb.net code). Now, ALL AND EVERY file reference MUST be a full normal standard windows path name!!!
so, if say your vb.net code was to "test" if the above file existed?
Lets say we drop a button and a image control on a web page - we have this:
and lets just make this super simple - we want in vb code to set the above image control to a picture we have in our Content folder.
Well, you have to translate the web based url into a plane jane good old fashioned windows file path name!
So, you would do this:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strF As String
strF = "~/Content/uncheck1.jpg"
Dim strFInternal = Server.MapPath(strF)
Debug.Print(strFInternal)
If File.Exists(strFInternal) Then
Image1.ImageUrl = strF
End If
End Sub
Note how our INTERNAL code MUST use a good old plane jane windows file path name.
but for things on the web page? They are ALWAYS referenced from the point of view of the web site. After I run the above code I get this:
But that debug.print of the file name? This is the output:
Output:
C:\Users\AlbertKallal\source\repos\WebFriendlyTest\Content\uncheck1.jpg
Note VERY careful the above? It was a plane jane INTERNAL file name. I can't tell you how many times I struggled with above simple concept:
Web page controls and markup: use correct URL path names
Code behind: use full windows path name!!!
So, your posted code? it WILL work near as it stands!!!!
The only issue here is what folder you looking to push out to that list box?
Say in above, I wanted to push out ALL files in that Content Folder.
I mean, I can type in this to display that check box if I wanted to:
So the web page now displays that one simple image on the page - since I typed in the FULL correct url!!!
So, how about we drop a list box on the web form, and when we click our button, we display ALL files in that Content folder. Now I could "guess" the location of the file folder, but for ANY WEB page to use that folder, it HAS to be part of the web site folders (or sub folders). The web site can NOT just out of the blue map to steal or grab ANY file on the computer - those URL's can ONLY point to say root of the site + any sub folder.
So that content folder on this site is this:
So, as you can see, then I can type in a url that is the base site, and then that folder, and then that picture (uncheck1.jpg) that exists in that folder.
So, lets drop in a listbox, and push out all the files from that folder to the listbox on the form:
Our markup will be this:
So, just a button, and a list box.
And the button code for the Content folder? Well, we would use this:
(I removed the search part - but that is standard code - JUST like you ALWAYS used in the past!!!
So:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MainFldr = "~/Content"
Dim FldrInternal = Server.MapPath(MainFldr)
Dim SKfiles() As System.IO.FileInfo
Dim FldrInfo As New System.IO.DirectoryInfo(FldrInternal)
ListBox1.Items.Clear()
SKfiles = FldrInfo.GetFiles("*.*", IO.SearchOption.AllDirectories)
For Each MyFile In SKfiles
ListBox1.Items.Add(MyFile.Name)
Next
End Sub
I decided to NOT use the full path name - but I could have.
The output:
so just remember, that any web page? It can ONLY use files and things that are PART of the web site. And any url - even for a picture, file etc.? Then it MUST be a valid URL.
However, the code behind? It is NOT limited to JUST the folders and files from the root and sub folders. You can actually use your d: drive, or anything else that box on the network can get/grab/use/fetch. So the code behind is your plane jane windows code.
The web site URL and files from web pages thus can only use folders/files that are part of the web site. However, in some cases, say you had some other big server with folders for pictures and files - but your web site (and valid URL's) need to use that folder? Well, you then setup what is a called a virtual directory. This you quite much need to use IIS as opposed to using IIS express edition. (you can google for express edition + setup virutal folders).
Once that virtual folder is setup? It will look like any other sub folder in teh site - but they are not in the site anymore. (and this is also used for documents or PDF folders often too).
This is simply LOOKS like a sub folder, but it really is a folder that can point to any other folder on your computer network. of course this would only work if the final web server and published site location is running on a box on your server, and say not some hosting plan.
So one should code and NOT think in terms of full valid local server file names, but try to always think in terms of the URL, and the path name, and even path names in sub folders in that web site. But in all cases, the code behind operations are against plane jane valid full path names.
However, if you thought that debug.print of the simply .jpg file name was long or funny? Well, on a published server those file path names can be super crazy paths - but you NEVER care if you reference the folders as per above.
I solve the problem by creating search like below. searching folder name and subfolder.
Dim files As FileInfo() = Nothing
Dim dirInfo As DirectoryInfo = New DirectoryInfo(startFolder)
Dim dir As DirectoryInfo() = Nothing
dir = dirInfo.GetDirectories(folderName, SearchOption.AllDirectories)
For i = 0 To dir.Length - 1
If dir(i).Name = folderName Then
Dim path2 = Directory.GetDirectories(dir(i).FullName)
If path2.Length = 0 Then
files = dir(i).GetFiles()
For Each file In dir(i).GetFiles()
path = CStr(dir(0).FullName)
path = path.Remove(0, 11)
HiddenField1.Value = path & "\" & file.Name
HiddenField2.Value = file.Name
Dim tr As New TableRow
tr.Cells.Add(New TableCell With {.Text = file.Name})
grd.Rows.Add(tr)
Dim tdlnk As New TableCell
Dim lnk As New HtmlAnchor
tdlnk.Controls.Add(lnk)
tr.Cells.Add(tdlnk)
Next
Exit For
Else
Dim aaa As String = path2(0).Substring(path2(0).Length - 10)
startFolder = path2(0).ToString
folderName = aaa
Dim files1 As FileInfo() = Nothing
Dim dirInfo1 As DirectoryInfo = New DirectoryInfo(startFolder)
Dim dir1 As DirectoryInfo() = Nothing
dirInfo1.GetDirectories(folderName, SearchOption.AllDirectories)
files1 = dirInfo1.GetFiles
For Each file In dirInfo1.GetFiles
path = CStr(dirInfo1.FullName)
path = path.Remove(0, 11)
HiddenField1.Value = path & "\" & file.Name
HiddenField2.Value = file.Name
Dim tr As New TableRow
tr.Cells.Add(New TableCell With {.Text = file.Name})
grd.Rows.Add(tr)
Dim tdlnk As New TableCell
Dim lnk As New HtmlAnchor
tdlnk.Controls.Add(lnk)
tr.Cells.Add(tdlnk)
Next
Exit For
End If
End If
Next

View image from file in Asp.net

In one procedure I correctly create a bmp file called tempimage.bmp. I see the file in the folder, all right.
I would like to see this image in a control of the type System.Web.UI.WebControls.Image, called Image1.
I tried it like this:
string cPath = HttpContext.Current.Server.MapPath(".") + "\\";
Image1.ImageUrl = cPath + "tempimage.bmp";
I don't get any errors but I don't see anything. Where am I wrong?
If D:\DOTNET2019\Sicaweb\ is your root directory
Image1.ImageUrl = "/tempimage.bmp";
If it can change do
Image1.ImageUrl = Page.ResolveUrl("~/tempimage.bmp");
The problem was only the automatic publication of Visual Studio which clears the folder permissions every time.

DotNetZip download works in one site, not another

EDIT - RESOLVED: the difference was that in the "main" case the download was initiated via a callback cycle, and in the "test" case it was initiated through a server side button click function. My guess is that the download request and the callback cycle interfered with each other, both stopping the download and causing the page to become inactive (as described below). When I rewired the download on the main page to start with a submit instead of a callback, it did initiate the download.
This is in VS2013 Ultimate, Win7Pro, VB.Net, websites (not projects),IISExpress.
I built a test site to develop functionality for creating OpenXML PPTX and XLSX memorystreams and zipping and downloading them using DotNetZip. Got it to work fine. I then merged all that code into my "main" site. Both sites are on the same machine; I can run the test site and the main site at the same time. The main site processing is somewhat more complicated, but only in terms of accessing and downloading more files.
However, the Zip and Download function (below) works fine in the test site, but the exact same code doesn't work in the main site (with or without the test site up and running).
There's an error trap (see below) around the Zip.Save function where the download occurs but no error shows up.
Same overall behavior in Chrome, Firefox and IE11.
One peculiarity that might be a clue is that when the main site download fails, the server side functionality "goes dead". Local JS functions work, but the app doesn't respond to callbacks. When I do an F5 on the browser it works again.
I did a refresh on the DotNetZip package in the main site. The Zip object appears to be working properly, because it generates an error on duplicate file names.
I thought it might be the download function as written, however, it works in the test site. Also, another piece of the main site does a non-zipped download of a memory stream (included as the second code block below) and that works fine.
I thought it might be the data. So I kludged the main site to access, convert to memorystream and download the same file that the is accessed and downloaded in the test site. Still the main site download doesn't work.
When I compare the watch values on the Zip object in the two sites, they look identical. The length of the wrkFS.ContentStream is identical in both cases. The file names are different, however, they are:
Test_2EFVG1THK5.xlsx (main)
6-18_12-46-28_0.xlsx (test)
which are both legal file names.
EDIT: I saved the zip file to disk from the main program, instead of trying to download it, using this:
wrkFilePath = "D:\filepath\test.zip"
wrkZip.Save(wrkFilePath)
And it worked fine. So that possibly isolates the problem to this statement
wrkZip.Save(context.Response.OutputStream)
EDIT: Base on help I received here:
Convert DotNetZip ZipFile to byte array
I used this construct:
Dim ms as New MemoryStream
wrkZip.Save(ms)
wrkBytes = ms.ToArray()
context.Response.BinaryWrite(wrkByteAr)
to get around the ZipFile.Save(to context), and that didn't work either; no download, no error message, and page goes dead. However, at least I can now assume it's not a problem with the ZipFile.Save.
At this point I'm out of ways to diagnose the problem.
Any suggestions would be appreciated.
Here is the code that works in the test site but not in the main site.
Public Sub ZipAndDownloadMemoryStreams(ByVal context As HttpContext) _
Implements IHttpHandler.ProcessRequest
Dim rtn As String = ""
Try
Dim wrkAr As ArrayList
wrkAr = SC.ContentArrayForDownLoad
If wrkAr.Count = 0 Then
Dim wrkStop As Integer = 0
Exit Sub
End If
Dim wrkFS As ZipDownloadContentPair
Using wrkZip As New ZipFile
'----- create zip, add memory stream----------
For n As Integer = 0 To wrkAr.Count - 1
wrkFS = wrkAr(n)
wrkZip.AddEntry(wrkFS.FileName, wrkFS.ContentStream)
Next
context.Response.Clear()
context.Response.ContentType = "application/force-download"
context.Response.AddHeader( _
"content-disposition", _
"attachment; filename=" & "_XYZ_Export.zip")
'---- save context (initiate download)-----
wrkZip.Save(context.Response.OutputStream)
wrkZip.Dispose()
End Using
Catch ex As Exception
Dim exmsg As String = ex.Message
Dim wrkStop As String = ""
End Try
End Sub
Below is the non-zip download function that works fine in the main site.
It might be possible to convert the Zip content to a byte array and try the download that way, however, I'm not sure how that would work.
(SEE EDIT NOTE ABOVE --- I implemented a version of the below, i.e. try to download byte array instead of directly ZipFile.Save(), however, it didn't help; still doesn't download, and still doesn't give any error message)
Public Sub DownloadEncryptedMemoryStream(ByVal context As HttpContext) _
Implements IHttpHandler.ProcessRequest
Dim wrkMemoryStream As New System.IO.MemoryStream()
wrkMemoryStream = SC.ContentForDownload
Dim wrkFileName As String = SC.ExportEncryptedFileName
wrkMemoryStream.Position = 0
Dim wrkBytesInStream As Byte() = New Byte(wrkMemoryStream.Length - 1) {}
wrkMemoryStream.Read(wrkBytesInStream, 0, CInt(wrkMemoryStream.Length))
Dim wrkStr As String = ""
wrkStr = Encoding.UTF8.GetString(wrkMemoryStream.ToArray())
wrkMemoryStream.Close()
context.Response.Clear()
context.Response.ContentType = "application/force-download"
context.Response.AddHeader("content-disposition", "attachment; filename=" & wrkFileName)
context.Response.BinaryWrite(wrkBytesInStream)
wrkBytesInStream = Nothing
context.Response.End()
(Per the note now at the top of the question): The difference was that in the "main" case the download was initiated via a callback cycle, and in the "test" case it was initiated through a server side button click function. My guess is that the download request and the callback cycle interfered with each other, both stopping the download and causing the page to become inactive (as described below). When I rewired the download on the main page to start with a submit instead of a callback, it did initiate the download.

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

Creating a dynamic graphic in asp.net

I am busy creating a control in asp.net. The control consists of some text and an image. The image will be used to display a graph. The control gets the data for the graph by reading it from a database. It seems I have two options to display the graph in the image box. First, I can create a jpg from the data and save the file on the server. I can then load this file into the image box. I think this would cause a problem if various users try to access the site at the same time, so I don't think it is a good option. The other options is to create a file called output, that outputs the graph like this: objBitmap.Save(Response.OutputStream, ImageFormat.Gif)
I can then display the image like this in my control: Image1.ImageUrl = "output.aspx"
The problem that I am facing is how do I get the data from my control to the output page? As far as I know it is too much data to pass as a parameter. If there is another better method of doing it, please let me know
Thanks
You can write the image content to the response of output.aspx. Something like this (taken from one of my existing GetImage pages:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strFilename As String
strFilename = Request.QueryString("filename")
Dim strPath As String = AppSettings("ProxyImageSavePath") & strFilename
Response.Clear()
Response.ContentType = "image/jpeg"
If Not IO.File.Exists(strPath) Then
'erm
Response.Write("file not found")
Else
Response.WriteFile(strPath)
End If
Response.End()
End Sub
Edit: I've just realised this may not be the solution you're looking for; Your webserver should be able to cache this though.
You need handlers. See in this article, Protecting Your Images, section "Creating the ImageHandler HTTP Handler", you'll find the code how to write the handler, so it outputs an image. You don't need all, it's only an example.
You also need to register the handler in the web.config.
To reference it Image1.ImageUrl = "handler.ashx?graphdata=xxxx". Use QueryString to get the data source to generate the graph.

Resources