Checking if image exist in my local resources - c#

net/C# application I have list of items.
In the code behind:
I want to assign a picture from my local resources for each item. the items name and the picture names are the same.
The pictures are all in a "image" folder in my project.
Example of how I assign a picture to an item:
Item1.PictureUrl = "images/items/" + item1.Name + ".jpg";
I have items that don't have pictures. I want to assign for them a default picture.
I tried to check if the picture exists using this:
foreach(ObjectItem item in ListOfItems)
{
if(File.Exists("images/items/"+item.Name+".jpg"))
item.PictureUrl = "images/items/"+item.Name+".jpg";
else
item.PictureUrl= "images/Default.jpp";
}
But the File.Exists method is always returning false, even if the picture exist.
I also tried to use '\' instead of '/' but didn't work
How can I do it?
Thank you for any help

You need to convert the relative file path into a physical file path in order for File.Exists to work correctly.
You will want to use Server.MapPath to verify the existence of the file:
if(File.Exists(Server.MapPath("/images/items/"+item.Name+".jpg")))
Also, when you use Server.MapPath, you should usually specify the leading slash so that the request is relative to the web application's directory.
If you don't provide the leading slash, then the path will be generated relative to the current page that is being processed and if this page is in a subdirectory, you will not get to your images folder.

.Net Core Solution
1- Write this at the top of your View (Injecting IHostingEnvironment here);
#inject Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv
2- Write this to the place of image(Doing existence check);
var path = System.IO.Path.Combine(hostingEnv.WebRootPath, "MyFolder", "MyImage.jpg");
if (System.IO.File.Exists(path))
{
<img class="img-fluid" src="~/MyFolder/MyImage.jpg" alt="">
}

var path = $#"C:\Fotos\Funcionarios\1.Png";
FileInfo file = new FileInfo(path);
if (file.Exists.Equals(true))
{
//faz algo
}

Related

how to return image url instead of file path

I am facing an issue when showing uploaded image in browser.
I get error
Not allowed to load local resource:
file:///C:/Office%20Data/dummy/AngularJSAuthentication-master/MyCars/MyCar.API/App_Data/Images/p7.jpeg%20alt=
I wrote the following line of code to store image on server under App_data.
File.Path = Url.Content(string.Format("{0}/{1}", System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Images"), fileName));
File path saved in DB as following
file:///C:/Sample%20Data/dummy/AngularJSAuthentication-master/MyCars/MyCar.API/App_Data/Images/p7.jpeg
HTML
<img ng-src="{{motor.FileUploads[0].Path}} alt="Description" />
After googling i got the reason for this error.
Basically i need to return back Image URL instead of file path.
Problem:
I am not sure how i can return image path back to angular client.
Can someone guide me on it.
You don't need to specify the complete physical path, when reference from the browser
File.Path = Url.Content(string.Format("~/App_Data/Images/{0}", fileName));
this should return the relative URL
Update : well this won't work since you can directly access contents of the app_data folder. you can approach this either of these ways
move the images out of the app_data folder to like ~/images folder
and it should work or
keep the file in the app_data folder but stream the file using
content/file result action on one of your controllers
bare minimum sample implementation of the second option would look like
public class UploadsController : Controller
{
[HttpGet]
public ActionResult Image( string fileName )
{
//!validate file name!
return File( Server.MapPath( $"~/App_Data/{fileName}" ), "image/jpeg" );
}
}
then in the HTML it can be referenced as <img src="api/uploads/image?filename=temp.jpg" ...
Just drop everything except the file name if all your images are in the root of Images:
//using System.IO;
File.Path = Url.Content(string.Format("{0}/{1}", System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Images"), Path.GetFileName(fileName)));
Update
should have been like Sam's answer:
File.Path = Url.Content(string.Format("~/App_Data/Images/{0}",Path.GetFileName(fileName)));

File.Delete isn't working to delete image from sub folder

In our ASP.NET program a user can upload an image to a folder. The location of the image (including the name of the upload folder which is in the root directory) is stored as a variable called "path", ie. "Uploads/fileName.jpg".
To remove the image:
if (File.Exists("~/" + path))
{
File.Delete("~/" + path);
}
However, it fails to run because it can't verify that the file exists. Through some testing we noticed it's looking for "path" in the "system32" directory. Why would this be?
You need to use Server.Map path to ensure that the Tilde is resolved correctly.
MSDN Article is here -> http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx
Your code would become
var fixedPath = Server.MapPath("~/" + path);
if (File.Exists(fixedPath))
{
File.Delete(fixedPath);
}
The File class is not aware of the IIS directory mapping, so it won't understand ~ correctly. You have to first use a method to map the app relative path to a local path with Server.MapPath

asp file upload control, which one should be use?

ok, i found this on internet to upload some files.
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
and this
//check to make sure a file is selected
if (FileUpload1.HasFile)
{
//create the path to save the file to
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);
//save the file to our local path
FileUpload1.SaveAs(fileName);
}
what is the difference, which one to use? i got confuse. by the way, if i can store file path in database, and next time when i want to delete or see that file, how can i retrieve that? so let say, first i add a record to database and uploaded a .doc file / excel file, next time when i want to edit that record, i want to retrieve the uploaded file, and show it in UI. thanks.
use second one cause it will convert relative or virtual path to real path itself . .u should get path from db and use it to resolve the path the same way you are storing and do manipulation on it delete and etc. for displaying url="~/Files/yourfilename"
yourfilefromdb -u retrieve it from db
string filepath = Path.Combine(Server.MapPath("~/Files"), yourfilefromdb);
File.Delete(filepath);
for showing
if it accessible directly u can just write url="~/Files/yourfilefromdb"
The only difference in two code blocks posted you is in specifying file path.
In case 1, static location is specified to save the file. It can cause problem, if location to save files differ in your production environment. It will require rebuild in that case.
While, in case 2, location is specified using relative path. So, it will always save files at "/Files" location.
//if you already know your folder is: E:\ABC\A then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/ABC/A and you want to know the real path in the disk...
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(#"E:\Project\Folders", FileUpload1.FileName);// they know the right path so .they using directly
FileUpload1.SaveAs(fileName);
}
if (FileUpload1.HasFile)
{
string fileName = Path.Combine(Server.MapPath("~/Files"), FileUpload1.FileName);// i don't know path is correct or not so they using Server.MapPath. . .
FileUpload1.SaveAs(fileName);
}

How to properly use File.Exists in windows application

I have a windows application with an "images" folder. I need to check if an image exists, which it will, during runtime. The below code is what I have but it always returns false.
if ( File.Exists("images/" + item.tool_image) )
{
Image img;
img = Image.FromFile("images/" + item.tool_image);
titem.Image = img;
}
Whats the problem or the proper way to do this.
If the file you're looking for doesn't exist in the working directory of your application, call File.Exists with a fully-qualified path:
if (File.Exists(#"C:\images\" + item.tool_image))
{ ... }
Of course, verify that a file actually exists at that location.
You'll find life easier if you use the tools provided by the Path class:
if (File.Exists(Path.Combine(#"C:\images", item.tool_image)))
{ ... }
The path is wrong try to change it to
string basePath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string imageFileName = System.IO.Path.Combine(basePath, "Images",item.tool_image);
if ( File.Exists(imageFileName) )
{
Image img;
img = Image.FromFile(imageFileName);
titem.Image = img;
}
How to properly use File.Exists in windows application?
You don't!
It's almost never appropriate to check if a file exists before trying to open. There are other things at work here: permissions, locking, sharing, time.
Instead, the correct way to do this is to try to open the file, whether it exists or not, and then catch the exception if your attempt to open the file fails. You have to be able to handle this exception anyway, even after performing the File.Exists() check. This makes your initial File.Exists() check not only redundant to your code, but wasteful, because it causes an extra trip out to the file system... and there's not much you can do in programming that's slower than going to the file system.
it is looking from the location where the code is currently running, also the '/' is the wrong direction. also, you are defining the path in multiple places, which can lead to problems later.
var path = string.Format(#"c:\somewhere\images\{0}", item.tool_image);
if (File.Exists(path))
{
Image img;
img = Image.FromFile(path);
titem.Image = img;
}
it's up to you to set the variable path , but in all likelihood, in your code example the location you expect isn't being checked.
The way you're calling it, you are looking for a file of whatever is in the string item.tool_image inside the images folder. Note that this images folder is located inside whatever directory contains your executable.
For instance, i just called File.Exists("images/image.jpg") and it worked.
As everyone has mentioned, use the fully qualified path. I also make heavy use of the Path.Combine, so I don't have to worry about missing a slash or two when I'm combining directories. The current executing directory is also useful...
File.Exists(Path.Combine(Environment.CurrentDirectory, "Images", item.tool_image));

getting file name and moving it

string fName = Path.GetFileName(tempPaths[z]);
if (!File.Exists(subAch + fName))
{
File.Move(tempPaths[z], subAch + fName);
Console.WriteLine("moved!!! from " + tempPaths[z] + " tooooo ");
}
tempPaths is a list with all the image file paths. e.g. ./images/image4.jpg
subAch is a directory string.
I wish to get the file name of the file then move them to another directory. But with the code above i kept getting error: file is being used by other process.
Is there anyway which get the file name and move them? I have tried fileStream but was confused by it.
Please advice.
Thank you!
Your code should work just fine. You just need to figure out who is locking the files.
I'd put the code inside the if-block in a try-catch block to deal with the locked files.
I will also recommend you to use Path.Combine instead of dir + file.
One thing: you are checking if subAch + tempPaths[z] exists, yet you are copying to a different location; subAch + fName.
File is being used by another process means exactly that. Someone/something is already using the file, so can't move it. You can always catch the error and moving everything else?
I have use a non-ideal way to grab the file name and move the files to another place.
tempPaths.AddRange(Directory.GetFiles(rawStorePath, filter, SearchOption.AllDirectories));
The code above gets all the directories of all the files in the folder set. The outcome with be something like this. tempPaths is a List.
"./images/glass_numbers_5.jpg"
"./images/G.JPG"
"./images/E.JPG"
"./images/F.JPG"
"./images/glass_numbers_0.jpg"
"./images/C.JPG"
"./images/B.JPG"
"./images/A.JPG"
"./images/D.JPG"
"./images/glass_numbers_7.jpg"
then after i use a loop to grab the file names.
for (int i = 0; i < tempPaths.Count; i++)
{
//Getting the original names of the images
int pLength = rawStorePath.Length;
string something = tempPaths[i].Remove(0, pLength);
if (!_tfileName.ContainsKey(tempPaths[i]))
{ _tfileName.Add(tempPaths[i], something); }
}
rawStorePath is the path of the targeted path e.g.: ./images/
tempPath[i] e.g. : ./images/G.JPG
So with the length i remove the letters and get the file name back.
Please advice me for a ideal way to do this if there is any.
Thanks!

Categories

Resources