I have set of files (which are essentially ".exe" files) that I allow the users to download from my website. To have a clearer picture have a look at the this screenshot (it is just a academic project). Now I have administrator privilege in which I can upload a new software file to a folder (componentsFolder) to the root of my website and I also add the filepath to the database table at the same time.
I'm using the following code to do that:
string componentRelativeFilePath = #"/ComponentsFolder/" + ComponentName;
I'm storing the filepath in the following format in the database file:
/ComponentsFolder/FileName.exe
What is the difference between storing the files in the following formats?
/ComponentsFolder/FileName.exe
\ComponentsFolder\FileName.exe
~/ComponentsFolder/FileName.exe
~\ComponentsFolder\FileName.exe
I'm using server.mappath to retrieve the file from the root folder.
I want to know the difference (in this context) between these formats and which one is the standard/appropriate/technically correct format to store the relative paths in database table.
In terms of Asp.Net lets suppose you set your image path as "/Image/pic1.jpeg" so the image would be searched in Image folder located in website root and in that folder pic1.jpeg is searched. If your set you image source to "~/Image/pic1.jpeg" in that case as well the image file is read from the Image folder that is located directly under the root of the Web application, regardless of where in the Web site the page is located. But '~/' this could only be used with server controls.
If path is "../Image/pic1.jpeg", in that case Image folder is searched in the current webpage's folder.
As per my opinion storing path in "~/Image/" format is a better choice in terms of Asp.Net.
Hope I answer your question.
Related
I am trying to upload an excel file into SQL server. The thing is I am stuck here
string fileName = Path.Combine(#"C:\", FileUpload1.FileName);
FileUpload1.SaveAs(fileName);
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", fileName);
The line
string fileName = Path.Combine(#"C:\", FileUpload1.FileName);
gives pathname as C:\FileName for which I get an exception that access is denied, and from this
Why is access to the path denied?
I got to know that we can get these errors if the path is a directory. I know my path is wrong, but I am clueless as how to select the correct path for further processing.
My asp.net code is
<asp:FileUpload ID="FileUpload1" runat="server" Width="368px" />
<p>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</p>
When I referred this
https://www.c-sharpcorner.com/blogs/how-to-import-excel-data-in-sql-server-using-asp-net2
and
https://www.aspdotnet-suresh.com/2012/12/aspnet-how-to-get-full-file-path-from.html
and changed my code to
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("Files/" + filename));
string filepath = "Files/" + filename;
I got Could not find a part of the path exception.
$exception {"Could not find a part of the path 'C:\\Users\\AMEN\\source\\repos\\ExcelDatabase\\ExcelDatabase\\Files\\New Microsoft Excel Worksheet.xlsx'."} System.IO.DirectoryNotFoundException
I then referred to the following also -
How to get the path of a file which is in file upload control in asp.net
but same error
I then inspected the path in the inspection and found out that it is incorrect --
C:\\Users\\AMEN\\source\\repos\\ExcelDatabase\\ExcelDatabase\\Files\\New Microsoft Excel Worksheet.xlsx'
I dont know why it entered the repos folder when I selected my excel from the desktop. But I know it appended file directory because of the following line
FileUpload1.SaveAs(Server.MapPath("Files/" + filename));
So I commented it out but then again too, it took the wrong path and I got the same exception . Please suggest me what should I do.
Thanks
Ok, this OFTEN comes down to the developer flpping between URL, web based URL's, and then code behind.
The way it works (to avoid confusing) is:
Any URL, and links and sources used in a web page markup?
You use and think and consider that a valid URL path name.
So, if you have a folder on your web site called MyFiles, then any URL (web and markup) is this:
www.mysite.com/MyFiles/dog.png
So, any reference in web markup = a web path, or relative web path.
But, in code behind?
You ALWAYS BUT ALWAYS use plain jane FULL windows path names in code to deal with a file.
So, failure to "flip" between the above contexts are what is the source of confusing in the vast majority of cases.
Next, keep in mind that file(s) up-loaded don't contain a path name, since information about the client side computer is not exposed and it not YOUR business anyway.
So, if I want a web link to any file in MyFiles - the it is web based URL (given our new rule above).
But, in code?
You can "translate" any web based URL to a internal plane jane windows file path, and code behind MUST USE windows path names, and they are in general to be FULL path names.
So, typical code to deal with a up-loaded file will look like this:
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string LocalFile = Server.MapPath(#"~/Files/" + filename);
FileUpload1.SaveAs(LocalFile);
So, two things:
You missed the "~/" to start from root.
You NEED to use # for the string, since the slashes etc. are escaped characters in c#, and you WANT to avoid any issue in that area -- so use #"my string" for such cases that will have things like slashes in the string.
So above assumes you have a folder nested in the root web site, and it called MyFiles.
Often, and in most cases, you CAN save the file to ANY location you want (assuming the web server has permissions to the folder that NOT nested in or part of the web site).
This idea in fact is often used, since then no valid web URL's to the file(s) can be had or even exist from the web site to that file folder.
You can expose the file folder if you map a "virtual" folder in IIS, and this is often done. But EVEN better is to NOT map such folders to the web site, and then ALWAYS use code behind to allow downloading of such files, since then that is a big jump in security. (users cannot type in any URL to get and download a file in such folders. Only code behind can dish out such files to the users for download - exactly what we want for security in most cases.
So, use server.MapPath to convert the nested MyFiles folder into a valid windows path name. However, if the folder is outside of the web site, then you don't use Server.MapPath, but simple use and have your own windows path name to some file folder on the computer, or even on the same network that the web server is running on.
And the LAST suggeston to save bugs and world poverty?
BE VERY careful with Server.MapPath, it runs from your CURRENT PAGE context!
That means if you move a page (and more important code behind) to a different nesting then Server.MapPath will produce values RELATIVE to that page!!!!
As a result, to save world poverty and bugs? You would do VERY well to not use
Server.MapPath(#"Files/") -- bad idea!!!
And ALWAYS use this:
Server.MapPath(#"~/Files/") -- good idea.
So, MapPath uses the current nesting of the URL that your current page and more important the code behind is running under. So, avoid relative path names for MapPath. There are use cases where you want this to occur, but the WHOLE point is that relative context of the current page DOES occur when using mappath - it not absolute from root UNLESS YOU assume as such and introduce the "~/" part into this mix, and you should!!
I'm looking to do this exactly :
set src property in view to a url outside of the MVC3 project
Fine but in web form ?
I tried simply putting the path as a string into the src of the image :
<asp:Image ID="imgInside" runat="server" src="\\serverName.com\dfs$\APPL-ADM\FichiersDev\MandatsInfo\SAR220-2020_1.jpg" >
Obviously not working, so I made src pointe on this function I wrote like so :
<asp:Image runat="server" Width="160px" src='<%# getImage(Container.DataItem as MandatMobile.DAL.MandatsEcoleCC_Result) %>' ></asp:Image>
In back end C# :
protected Byte[] getImage(MandatsEcoleCC_Result p)
{
using (MandatsDatas db = new MandatsDatas())
{
GROUPE_ARTICLE g = db.GROUPE_ARTICLE.First(t => t.ID_GROUPE == p.ID_GROUPE);
if (string.IsNullOrWhiteSpace(g.image))
return null;
FileStream fs = null;
try
{
fs = new FileStream(#"\\serverName.com\dfs$\APPL-ADM\FichiersDev\MandatsInfo\" + g.MANDAT.NO_MANDAT + g.image, FileMode.Open, FileAccess.Read);
}
catch
{
}
BinaryReader br = new BinaryReader(fs);
return br.ReadBytes((int)fs.Length);
}
}
Still not working, I've been searching but I just can't figure it out and I'm stuck trying all sorts of non-sens.
Well, you confusing two things:
Code behind:
Anytime you run code that uses a file, then you writing 100% server side code. As such any file path is a proper windows FULL qualified path name. It has ZERO ZERO to do with web URL's.
Read the above a dozen times. Your code does not use URL path names - end of story.
Web site:
Anytime you reference a file, picture, script files or anything? You are and MUST use a URL based on the path names of the web site, and more so path names that resolve to the folders that represent the site.
root:
\Pictures (say a folder in the web site folder list with pictures.
So, a src, or ANY URL in the web site? They do NOT use windows path names like code behind.
So, if there is a cat.png picture in folder pictures? When your URL will be this:
www.mywebsite.com/Pictures/cat.png
If you write code to read/load/see/use that cat.png picture? Then you convert in code from that extenral URL to a full qualifed standard windows path name (with back slaches).
So, in code behind if you want to read, or do somthing with the above file?
You use
dim strFile as string
strFile = Server.MapPath("www.mywebsite.com/Pictures/cat.png")
map path will now return a full qualified windows server path
eg:
c:\inetpub\wwwrootmysite\Pictures\cat.png
Ok, so now we realize that to use a VALID link to pictures on teh web site, we MUST use a valid URL.
So, what happens if say we have a network connected HUGE massive say SAN drive or some other huge server on the network that has huge storage, and has our pictures in that site?
Say:
\SANSERVER\WebPictures\cat.png
Well, obviosity that file folder can't be used in a URL. ONLY URL's in the web folder path name can be used. And this is a good thing. Since when I go to www.amazon.com it is a VERY good thing I can't type in a URL to get at their intenral accouting files server and steal all the credit card information of all customers.
So, now, how can I get at that cat.png, and turn it into a valid URL?
There are two ways:
One:
You make the decision to expose and INCLUDE the above path name as part of the web site. This is typical done with what is called a virutal folder. You need IIS, and during development with IIS + Visual Studio, it is a "pain" to setup such path names. But if you have full version of IIS, then you can add the virutal folder to the web site though the IIS user interface tools.
So, you add a virutal folder called MyPictures, and it will be mapped to:
\SANSERVER\WebPictures\cat.png
So, now the web site URL becomes:
www.mycoolsite.com/MyPictures/cat.png
And in code if you do a server.map path, the above url will return this:
\SANSERVER\WebPictures\cat.png
Ok, next issue:
I don't want to expose that other folder to the web site. I don't want a valid URL, and I don't even want users to be able to type in say this:
www.mycoolsite.com/MyPictures/doggie.png
So, if you DO expose another folder or add a folder to the web site hiarchy, then users ARE FREE to type in a URL that will resolve to that other folder (but you are assumed to have added a virtual folder to the web site).
Now, with a valid URL resolution, then you can place markup code on teh web site, and provide valid full URL path names to the picture or whatever for the web site.
However, lets say for reason of security, I do NOT want that other server to be exposed to as a URL?
Well, it it is NOT exposed as a valid web URL folder, then you can NOT put in a valid URL - it that's simple.
However, that don't mean the code behind can't read/load/open that file on the server. In fact the web site code behind can often read any file on the server, and in fact read any file anyplace on the network that the web server is running. And as noted, code behind does not use URL
s, and does not use "forward" "/" for the file - but a plan jane old fashting fully qualfied windows path name.
Since the code behind can darn near read any file and do anything it wants?
Ok, then how can we get the code behind to dish out a file, or send that file to the web site?
Two simple ways:
Your code behind could read the cat.png file, and copy it to a folder that is part of the web server folder layout. Once one, then you can provide a valid URL. However, with a huge picture library, that would be pain full.
And in some cases the picture might come from a database row(s) that store pictures, and once again no valid path name exists for the web site.
So, what you can do is read the file in code behind and then "stream" the data directly to the web site.
When you steam contents from code behind, then you don't care nor even require a valid URL, because the code behind is pumping out the object data (in this case a picture cat.png) directly to the web browser. So this is often done because your pictures don't even exist in a file, or in fact it not practical to include that folder in the web site folder list for reasons of security.
As noted, if this was/is just a folder of pictures OUTSIDE of the folders for the web site? Well then 99% of the time, then adding a mapped folder (a virtual folder) to the web site that points to the picture hard drive is common done, and is practical.
however, you might have a HUGE library of pictures on a big file server, and you have a database that has key words for searching the pictures, and the database row stores a valid path name to the hard drive/server that has all the pictures in a Hodge podge folder hierarchy that is not practical to expose as web based urls.
So, how to stream a file?
You code is close, but you need to include additional information. And unfortantly the server can't stream the file down as 100% binary format.
So, say we drag + drop a image control onto the form. You have this:
<asp:Image ID="Image1" runat="server" />
So, now in code behind to stream + set the picture to a picture on the hard drive?
You can use this:
Dim strFile As String = "c:\Test4\pcards.bmp"
Me.Image1.ImageUrl = Gimage2(strFile)
Now of course the URL path name to the above Test4 folder does not exist.
Gimage2 - it just converts the file as a byte array, and then to a string coded as base64.
Function Gimage2(strPath As String) As String
Dim PicData As Byte() = Nothing
PicData = File.ReadAllBytes(strPath)
Dim ContentType As String = "image/" & Path.GetExtension(strPath)
Return "data:" & ContentType & ";base64," & Convert.ToBase64String(PicData, 0, PicData.Length)
End Function
So I spent some time with a long post. The reason is you attempted to use a URL with standard windows back slashes, and that means in your mind, you are using the concept of a windows full path name and MAJOR confusing that with a URL path name. Failure to make this distingishing will cause you years of pain and suffering. You must have BEYOND CRYSTAL clear this concpet of a URL and that of a file name in code behind. They are two VERY different things.
If that addtional folder is "ok" to expose to the web site? Then create a Virtural folder.
That means:
wwww.mycoolsite.com/MyPictures/dog.png
Could in fact point to ANY mapped folder on your server. And this means the web server will require permisions to that folder, and in most cases thus a user (or your code) can type in and use a full web path name to the picture.
However, as noted, for pdf documents and many other types of files, then it is out of the question to have a valid URL and a mapped folder. So you can use the 100% file based approach as per above, and read the file as bytes, and then stream + output the file to the browser.
You can even do a response.write and pump out the file directly to the browser, but then again you don't have much control as to where it will be. Do realize that pumping out a string as base 64 data as per above can and will cause some bloat and expansion in the size of the string sent to be rendered as a picture. So for a simple image - sure that's ok. But for a larger high quality high resolution image, then of course I don't recommend you send the picture as a base64 string due to the expansion that string will result in.
I ended up putting a fonction in another MVC project that works correctly to retrieve images.
So my src path point on an URL instead of a file on a server path.
src='https://NameOf_MVC_webSite.csdn.qc.ca/imageBank/ForMandat?name=' + (Container.DataItem as MandatMobile.DAL.MandatsEcoleCC_Result).image
Dirty solution using another deployed app that has a (better / easy to use / functional) framework
But this is not an "OK" solution
My Debugging screenshot
I am trying to delete a file in asp.net web 4.7.1. I'm using FileInfo and checking if file exists using a relative path the points to the Uploads folder and image full name and extension. I have saving the image path in my database and I know if I use full path I will delete the file. How can I delete using the saved path?
I am thinking of modifying my database for each Image to store full path and relative path. I will use the full path for deleting file only. How can I delete without having to create a second database field for storing a full path?
One of the best ways to solve such problem (So that application wouldn't face any challenge of path access or read\write access on windows drive level).
Create virtual director and use that virtual directory to save relative path. Set up all access on virtual directory which is one time task.
Then you can use that virtual directory relative path in your code instead of full path.
I am using this code for creating pdf viewer in my application
https://amitpatriwala.wordpress.com/2009/08/28/pdf-viewer-in-asp-net/
it works fine when I give it a path for a file inside my application folders, ex: displaypdf1.FilePath= #"~/MyFolder/" + Hello.pdf;
but now I want to give this displaypdf1.FilePath an absolute path to read the pdf file which is not in my application folders, I tried but it didn't work!
A web page cannot access items that are outside of the website. If you want the web page to reference files located in D:\PDFs, for example, you need to create a virtual directory in your website that points to "D:\PDFs". Then the web pages can access them by ~/PDFs/Hello.pdf.
You'll also need to ensure that the website has appropriate permissions to access the directory.
I need to display an Image in web page. But the Image doesn't exist in the Web directory. If the image is under web directory I know that just "../Images/TN/my.jpg" will work. But the image is available in "D:\Images\TN\my.jpg" and My web site is deployed in "C:\apps\mywebsite".
How do I convert the "D:\Images\TN\my.jpg" path to a relative path so that the Image will be visible in web page?
You cant show images if they are not in a virtual directory.
Try holding then in your application folder itself or if its not feasible then make your Folder holding the image as a virtual directory in the IIS and mount it in your application folder.
Here's what you need to do (way i prefer),
Open IIS manager.
In Connections under Sites Select your Website and RightClick on it.
Select `Add Virtual Directory`... from the Context menu.
In The dialogue box that opens Enter the Alias name of your choice like **`"GlobalImages"`**
Browse the physical path of the Folder you want to and Select it and Click OK.
You will have it available for relative url in that website. like
www.example.com/GlobalImages
When you set that in IIS, it is automatically added to your Solution's Project.
Here is the MSDN link if you want..
http://msdn.microsoft.com/en-us/library/ms751432.aspx
Easiest thing to do is probably set up a handler and use the generic image name. While local, point to the D:. While on the server, point to the web path. (At least so long as you're not keeping them within the virtual directory that is).
TO fetch this point, we always write the absolute directory for images or other resource.But if the resource in the web server, i use the relative directory.