In my c# class I wrote I have a photo property that returns the photo source if the image exists (nothing or default image otherwise). In my code I use:
public string Photo
{
get
{
string source = "~/images/recipes/" + id + ".jpg";
if (File.Exists(source))
return "~/images/recipes/" + id + ".jpg";
else
return "";
}
}
If I get the FileInfo() information for this image I see that I tries to find this image in the following directory: C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\~\images\recipes
Of course the image is not located in that directory and File.Exists is returning me the wrong value. But how can I fix this?
Try this:
if(File.Exists(System.Web.HttpContext.Current.Server.MapPath(source)))
You need to map the relative path back to a physical path:
string source = HttpContext.Current.Server.MapPath("~/images/recipes/" + id + ".jpg");
You'll have to use:
Server.MapPath(source)
As you can not be 100% sure where the code will be running from, ie. it will be different in development and on a production server. Also are you sure ~/ works in windows? Wont that just be interpreted as a directory named ~? Unless thats what you want.
Related
I am using the media plugin for xamarin forms (by james montemagno) and the actual taking of the picture and storing it works fine, I have debugged the creation of the image on the emulator and it is stored in
/storage/emulated/0/Android/data/{APPNAME}.Android/files/Pictures/{DIRECTORYNAME}/{IMAGENAME}
however in my app it will get a list of file names from an API I want to check if the image exists in that folder.
The following works fine on IOS
var documentsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, App.IMAGE_FOLDER_NAME);
jpgFilename = System.IO.Path.Combine(jpgFilename, name);
I have tried the 2 following methods for getting it on android but both are incorrect
var documentsDirectory = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, App.IMAGE_FOLDER_NAME);
jpgFilename = System.IO.Path.Combine(jpgFilename, name);
Java.IO.File dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DataDirectory + "/" + App.IMAGE_FOLDER_NAME + "/" + name);
dir ends up as
/storage/emulated/0/data/{DIRECTORY}/{IMAGENAME}
jpgFileName ends up as /data/data/{APPNAME}.Android/files/{DIRECTORYNAME}/{IMAGENAME}
I dont want to hardcode anything in the paths but neither of these are right. I could not find anything in the GIT documentation for getting the file path except by looking at the path of the file created when taking a picture
The problem
I had the same kind of issue with Xamarin Media Plugin. For me, the problem is:
we don't really know where the plugin save the picture on android.
After reading all documentation I found, I just noted this:
... When your user takes a photo it will still store temporary data, but also if needed make a copy to the public gallery (based on platform). In the MediaFile you will now see a AlbumPath that you can query as well.
(from: Github plugin page)
so you can save your photo to your phone gallery (it will be public) but the path is known.
and we don't know what means "store the temporary data".
Solution
After investigating on how/where an app can store data, I found where the plugin stores photos on Android >> so I can generate back the full file names
In your Android app, the base path you are looking for is:
var basePath = Android.App.Application.Context.GetExternalFilesDir(null).AbsolutePath
It references your app's external private folder. It looks like that:
/storage/emulated/0/Android/data/com.mycompany.myapp/files
So finally to get your full file's path:
var fullPath = basePath + {DIRECTORYNAME} + {FILENAME};
I suggest you to make a dependency service, for instance 'ILocalFileService', that will expose this 'base path' property.
Please let me know if it works for you !
I resolved a similar problem. I wanted to collect all files for my app in a folder visible to all users.
var documentsDirectory = Android.OS.Environment.GetExternalStoragePublicDirectory(
Android.OS.Environment.DirectoryDocuments);
If you want to create Directory, add to your class using System.IO; and you have the same functions in a normal .NET application.
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
If you want to create files or directory, you can use PCLStorage.
public async Task<bool> CreateFileAsync(string name, string context)
{
// get hold of the file system
IFolder folder = FileSystem.Current.LocalStorage;
// create a file, overwriting any existing file
IFile file = await folder.CreateFileAsync(name,
CreationCollisionOption.ReplaceExisting);
// populate the file with some text
await file.WriteAllTextAsync(context);
return true;
}
to get the private path
var privatePath = file.Path;
to get the public Album path
var publicAlbumPath = file.AlbumPath;
se the documentation here https://github.com/jamesmontemagno/MediaPlugin
I have a Member Register aspx page.
ACCOUNT(user,pass,mail,privilege)
When a user is registerd sucessfully, if the privilege == "lecturer" --> a folder is created which folder's name= user.
Take a look at my code below:
if(privilege=="lecturer")
{
string path = this.Server.MapPath("~/Lecturer/"); // path="D:\\C#Projects\\website\\Lecturer\\"
string targetPath = path + #"\";
System.IO.Directory.CreateDirectory(Server.MapPath(targetPath+newuser));
}
It has an error: 'D:/C#Projects/website/Lecturer/david' is a physical path, but a virtual path was expected. Why???
I really want to create a david folder in Lecturer folder. Help???
You do not need to use Server.MapPath again as you have already converted the virtual path to physical path.
Change
System.IO.Directory.CreateDirectory(Server.MapPath(targetPath+newuser));
To
System.IO.Directory.CreateDirectory(targetPath+newuser);
If you already have a physical path D:\\C#Projects\\website\\Lecturer\\, it doesn't make sense to call Server.MapPath
You can try this:-
var files = Directory.GetFiles(#"D:\C#Projects\website\Lecturer");
or simply try this:-
System.IO.Directory.CreateDirectory(targetPath+newuser);
my code is:
string filename = FileUploader.PostedFile.FileName.Substring(fuImage.PostedFile.FileName.LastIndexOf("\\") + 1);
if(fuImage.HasFile)
{
FileUploader.SaveAs(Server.MapPath("Modules/NewUserProfile/UserPic/" + filename));
imgUser.ImageUrl = Server.MapPath("Modules/NewUserProfile/UserPic/" + filename);
}
imgUser is id of asp:Image Control.Image is uploaded in desire folder but its not display image in image control.What i am doing wrong here? Is there any postback issue.Thanks.
Use relative path for ImageUrl property.
imgUser.ImageUrl = "Modules/NewUserProfile/UserPic/" + filename;
OR use root operator ~ if Modules folder is located at root of web-app.
imgUser.ImageUrl = "~/Modules/NewUserProfile/UserPic/" + filename;
To run this code please understand the following things:
Server.MapPath() is used for getting physical Path like: D:/Img/Upload/..
so it is good idea to get path for saving image.
But in the case when you are getting the image for binding it to image control then you must have to use virtual path instead of Physical path.
Virtual path like: localhost/demo/upload/myimage.jpg.
I usually debug problems like this by first doing a view-source with your browser, and making sure the URL in the HTML source is what you expect. Then try copying the url that shows up in your view-source and pasting it into the address bar of your browser, and see if it shows up.
I think you should wait for the image to completely upload and then set the Image path to the image.
Also after rendering into the Browser use FireBug in Mozilla or Chrome Inspect Elemnt to check whether the Image has been rendered properly by looking at the image. If it broken then your image path is wrong. Try to give relative path and check.
newpic.ImageUrl = Page.ResolveURL("~/Pictures")+filename;
Server.MapPath returns physical drive location which is not useful when you are assigning to the imageurl.
I have a little question about my URL .
I use a tree view on my asp page that's why I use this getcurrentdirectory .
//DirectoryInfo di = new DirectoryInfo("~" + GetTheCurrentDirectory
(selectedNodeValue));
~ = C://Inetpub//WwwRoot//
GetTheCurrentDirectory = Projects//Folder1//
So for the moment it's fine because i Can load all the files for a folder.
After I try to download the files when you click on it .
protected void Page_Load(object sender, EventArgs e)
{
string path = Request["path"].ToString();
string filename = Request["file"].ToString();
fileDownload(filename, Server.MapPath("~\\" + path + filename));
}
So I can retrieve the Path wich is the current directory . The method I use in my other page.
In the server.MapPatch should I put ~ also ? Because when I do that is works localy, but when I put this on my server , the downloading part doesn't work so I suppose this is a URL issue, I can't debug so I am really lost about this !
I changed some things :
DirectoryInfo di = new DirectoryInfo(GetTheCurrentDirectory(selectedNodeValue));
So its returns the same thing .
So now in the server.MapPath the path equal something like Projects//Folder 1//
It works locally, but still not on the server ...
Try this:
fileDownload(filename, Server.MapPath("~/" + path + filename));
And also, as a best practice, don't use + to concatenate strings. You should use string.format, so I would write the above line as follows:
fileDownload(filename, Server.MapPath(string.format("~/{0}{1}", path, filename)));
Just to help you understand your problem better, Server.MapPath will return you a physical file path on the server which corresponds to the virtual path on the web server. i.e. it converts "http://website.com/img.jpg" to something like "C:\mywebsite\img.jpg"
UPDATE:
Make sure the folder you're trying to save the file to, is not read-only and you have permissions to create files in the folder.
I use asp.net 4 and c#.
I have this code that allow me to find the physical path for an image.
As you can see I get my machine physical pagh file:///C:.
string pathRaw = HttpContext.Current.Request.PhysicalApplicationPath + "Statics\\Cms\\Front-End\\Images\\Raw\\";
Result:
file:///C:/......../f005aba1-e286-4d9e-b9db-e6239f636e63.jpg
But I need display this image at the Front end of my web application so I would need a result like this:
http://localhost:1108/Statics/Cms/Front-End/Images/Raw/f005aba1-e286-4d9e-b9db-e6239f636e63.jpg
How to do it?
PS: I need to convert the result of variable pathRaw.
Hope I was able to express myself unfortunately I'm not sure about terminology in this case.
Thanks for your help!
The easiest thing to do is get rid of the physical application path.
If you cannot do that in your code, just strip it off the pathRaw variable. Like this:
public string GetVirtualPath( string physicalPath )
{
if ( !physicalPath.StartsWith( HttpContext.Current.Request.PhysicalApplicationPath ) )
{
throw new InvalidOperationException( "Physical path is not within the application root" );
}
return "~/" + physicalPath.Substring( HttpContext.Current.Request.PhysicalApplicationPath.Length )
.Replace( "\\", "/" );
}
The code first checks to see if the path is within the application root. If not, there's no way to figure out a url for the file so an exception is thrown.
The virtual path is constructed by stripping off the physical application path, convert all back-slashes to slashes and prefixing the path with "~/" to indicate it should be interpreted as relative to the application root.
After that you can convert the virtual path to a relative path for output to a browser using ResolveClientUrl(virtualPath).
Get the root of your application using Request.ApplicationPath
then use the answer from this question to get a relative path.
It might need a bit of tweaking but it should allow you to do what you're after.
Left-strip your pathRaw content by the Request.ApplicationPath and construct the url using
Uri navigateUri = new Uri(System.Web.HttpContext.Current.Request.Url, relativeDocumentPath);
Make use of
ApplicationPath - Gets the ASP.NET application's virtual application root path on the server.
Label1.Text = Request.ApplicationPath;
Image1.ImageUrl = Request.ApplicationPath + "/images/Image1.gif";
You can use Server.MapPath for this.
string pathRaw = System.Web.HttpContext.Current.Server.MapPath(“somefile.jpg“);