How to get filepath with Uri without "file:///" - c#

I get an image path with Uri, which is used as the source path in a report. This image is also loaded in an imagebox. The problem is that Uri adds "file:///" to the path. Therefore the image cannot be displayed on the report. How can I get the image path without that portion?

Use Uri.LocalPath:
Gets a local operating-system representation of a file name.
Just tested this in fsi:
> let u = new Uri("file:///C:/Users/Public/Test.png");;
val u : Uri = file:///C:/Users/Public/Test.png
> u.LocalPath;;
val it : string = "C:\Users\Public\Test.png"
Looks good.

If you just want to remove "file:///" from Uri try:
string uriPath =... //your path with "file:///"
string path = uriPath.Replace("file:///", "");

Related

Set webrowser control url to embedded html file?

I am trying to set a webbrowser control URL to an HTML file named "HomeHTML.html" that is embedded into the application. I can't figure out how to target it to set the new URL.
webbrowser.Url = new Uri(HomeHTML.html); //dosen't work
I solved my problem, if anyone else has the same problem this code will work.
string currentDirectory = Directory.GetCurrentDirectory();
string filePath = System.IO.Path.Combine(currentDirectory"home.html");
webBrowser1.Url = new Uri(filepath);

Using a Resource Image as the value in RDLC Parameter

I'm trying to pass an image as a parameter to an Image in a RDLC Report. I tried using the following:
string imgPath = new Uri("pack://application:,,,/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri(AppDomain.CurrentDomain.BaseDirectory + "pack://application:,,,/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri("/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri(AppDomain.CurrentDomain.BaseDirectory + "/Resources/default_product_img.png").AbsoluteUri;
string imgPath = new Uri("pack://application:,,,/Resources/default_product_img.png", UriKind.Absolute).AbsoluteUri;
string imgPath = new Uri(HttpContext.Current.Server.MapPath("~/Resources/default_product_img.png")).AbsoluteUri;
string imgPath = new Uri(HostingEnvironment.MapPath("~/Resources/default_product_img.png")).AbsoluteUri;
but the display always show the red X when I run it. I managed to make this work, but the source of the image is in the same level as the .exe and not inside it.
I also tried creating a BitmapImage, but ReportParameter() only accepts strings.
Is there a way for this to work? Or should I just copy it beside the .exe file?
Things to Note:
The image source is set as External
default_product_img.png is inside Resources folder and has a Build Action of Resource
The parameter name is set as the value in Use this image:
Take the image as a bitmap and save it to a memory stream then convert the memory stream into a base64 string. Pass this string into the parameter and use that parameter as the image. In the RDLC set the image source to be database and make sure the mime type is a correct match for how you saved the bitmap to the memory stream.
string paramValue;
using (var b = new Bitmap("file path or new properties for bitmap")) {
using (var ms = new MemoryStream()) {
b.save(ms, ImageFormat.Png);
paramValue = ConvertToBase64String(ms.ToArray());
}
}
Or if you want to keep it as an external file set the image source to be external in the rdlc and pass the path to the image as file://c:\site\resources\default_product_img.png it will need to be an absolute path and you can use Server.MapPath to convert the web relative path to an absolute local path then just make sure you have file:// at the beginning of the path so the report engine knows it's a local path.

Dynamic file paths and Image command

I am trying to create a file path, at the end of which will be a "images" folder that the program will use with the Image command to load jpeg files.
I want the program to dynamically know to load the jpeg files from the image folder where ever the executable is launched.
I was able to find this on this site, I added the 2 bottom code lines:
public static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return System.IO.Path.GetDirectoryName(path);
}
}
public static string imagePath = #"\images";
public static string finalImagePath = AssemblyDirectory + imagePath;
If I set a break point, the 'finalImagePath' is:
"C:\Users\My Name\Documents\Visual Studio 2010\Projects\Universal Serial Diagnostics\bin\Debug\images"
Which is correct, but how do I incorporate that with:
Image image = Image.FromFile(#"C:\Users\My Name\Desktop\Dip\ENV500008.jpg");
Replacing the hard coded path with the dynamic path.
The ENV500008.jpg would be stored in the images folder.
Thank you.
string path = AppDomain.CurrentDomain.BaseDirectory + "ENV500008.jpg";
if (System.IO.File.Exists(path))
{
Image image = Image.FromFile(path);
// .. the rest of the code that uses the image ..
}
Image image = Image.FromFile(#finalImagePath + "\\ENV500008.jpg");
Image image5 = Image.FromFile(#finalImagePath + "\\ENV510829-2.jpg");
public static string GetAnyPath(string fileName)
{
//my path where i want my file to be created is : "C:\\Users\\{my-system-name}\\Desktop\\Me\\create-file\\CreateFile\\CreateFile\\FilesPosition\\firstjson.json"
var basePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath.Split(new string[] { "\\CreateFile" }, StringSplitOptions.None)[0];
var filePath = Path.Combine(basePath, $"CreateFile\\CreateFile\\FilesPosition\\{fileName}.json");
return filePath;
}
change .json to any type according to need
refer :https://github.com/swinalkm/create-file/tree/main/CreateFile/CreateFile

Date Taken of an Image C#

I need to rename my Image (.jpg) and the new name needs to include the date taken. I can get the date taken of the image but can not include it into new File name.
Image im = new Bitmap("FileName.....");
PropertyItem pi = im.GetPropertyItem(0x132);
dateTaken = Encoding.UTF8.GetString(pi.Value);
dateTaken = dateTaken.Replace(":", "").Replace(" ", "");
string newName = dateTaken +".jpg" ;
MessageBox.Show(newName.ToString());
So is the problem that you can't get the date into the string you're trying to show in the message box or are you trying to change the filename of the image? If you want to change the image filename, you have to modify the file itself. Look at Replace part of a filename in C#
If you would like to rename your jpeg file, you could try the code below.
This code will extract the date from an image (requires the image's full file path), convert it to a different format and then use it as a new file name. The code to rename the file is commented out, so that you can see the result in the console before trying it on your local machine.
Sample Code. Please use your own fully qualified file path
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
// This is just an example directory, please use your fully qualified file path
string oldFilePath = #"C:\Users\User\Desktop\image.JPG";
// Get the path of the file, and append a trailing backslash
string directory = System.IO.Path.GetDirectoryName(oldFilePath) + #"\";
// Get the date property from the image
Bitmap image = new Bitmap(oldFilePath);
PropertyItem test = image.GetPropertyItem(0x132);
// Extract the date property as a string
System.Text.ASCIIEncoding a = new ASCIIEncoding();
string date = a.GetString(test.Value, 0, test.Len - 1);
// Create a DateTime object with our extracted date so that we can format it how we wish
System.Globalization.CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateCreated = DateTime.ParseExact(date, "yyyy:MM:d H:m:s", provider);
// Create our own file friendly format of daydayMonthMonthYearYearYearYear
string fileName = dateCreated.ToString("ddMMyyyy");
// Create the new file path
string newPath = directory + fileName + ".JPG";
// Use this method to rename the file
//System.IO.File.Move(oldFilePath, newPath);
Console.WriteLine(newPath);

Randomly mapping an image in C# ASP.NET

Quite a bit of looking at this one.
I have an aspx web page with an Image control on it, and I want to load images from my web directory at random to diplay in the image control. The below is the code and how far I have got.
Seems a simple task to request an image file at random and display this in a web page, all I am receiving however is a local filepath (which appears to be no use to the Image Control) and no image on the webpage.
AppSettings.imageUrl returns: "~/Images"
Any suggestions would be appreciated.
protected void Page_Load(object sender, EventArgs e)
{
GetImage();
}
private void GetImage()
{
imgMain.ImageUrl = ResolveClientUrl(RandomImage());
}
private string RandomImage()
{
string mapPath = Request.MapPath(AppSettings.imageUrl);
var rand = new Random();
var files = Directory.GetFiles(mapPath);
return files[rand.Next(files.Length)];
Your RandomImage() method possibly doesn't return file path relative to current page. Either return
string fileName = Path.GetFileName(file[rand.Next(files.Length)]);
return AppSettings.imageUrl + fileName;
and then resolve it or resolve it right away
string fileName = Path.GetFileName(file[rand.Next(files.Length)]);
return Request.MapPath(AppSettings.imageUrl + fileName);
Do a View Source on the resulting page and see if the <img src="..."> is getting set to a sensible value.
On further investigation it seems that ResolveClientUrl takes a relative URL, not an absolute file system path. Therefore RandomImage should return something like:
return AppSettings.imageUrl + "/" + Path.GetFileName(files[rand.Next(files.Length)]);
You're getting the file names. The Directory.GetFiles could also be used in non-web application and therefore it would make no sense to treat the files as relative to your website root.
What you can do is get the local path for root of your site like this:
string root = Request.MapPath("~/");
and then remove that substring from the file you selected:
files[rand.Next(files.Length)].Replace(root, string.Empty);
That's all you need.

Categories

Resources