Dynamic file paths and Image command - c#

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

Related

How to change path to save output date ? it's only saving in form location

i need to change outlook_file location to network share drive
can you advice any solution ?
it will only save in form location
const string PATH = "C:\\Temp\\Formularz\\";
const string TASKS_FILE = "lista_zadan.txt";
const string USERS_FILE = "lista_uzytkownikow.txt";
const string OUTPUT_FILE = "dane.txt";
private void SaveToFile()
{
if (!File.Exists(PATH + OUTPUT_FILE))
{
using (StreamWriter sw = File.CreateText(PATH + OUTPUT_FILE))
{
sw.Write("Data\t");
sw.Write("Użytkownik\t");
}
and if i change OUTPUT_FILE location it doesnt work , it will save only if i leave OUTPUT location same as PATH
You would want to look at the File.Move Method i think it does exactly what you are trying todo.
Code would look something like this
string path = #"path_to_file";
string path2 = #"path_to_dest";
File.Move(path, path2)
If you want to change you log file output just change to path to the perfered File

Saving images to a project folder in asp.net/c#

In my method, I'm trying to save an image in a folder in the directory of my project. I have tried just putting the direct filepath of the folder, but that gives me an error when the project runs.
Is there a built-in extension of some kind in c# that would allow me to save this image in a folder in my directory; or way to simply access my directory without drilling to where my project is saved on my computer?
private void CreateBarcode()
{
var bitmapImage = new Bitmap(500,300);
var g = Graphics.FromImage(bitmapImage);
g.Clear(Color.White);
UPCbarcode barcode = new UPCbarcode(UPCbarcode.RandomGeneratedNumber(), bitmapImage, g);
string filepath=#"images/image1.jpg";
bitmapImage.Save(filepath,System.Drawing.Imaging.ImageFormat.Jpeg);
}
You can always use the AppData folder,
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Assuming the "Image" folder is in the root directory of your Project use:
Server.MapPath("~/Image" + filename)
you can check if the file already exist at a location by :
if (!File.Exists(filePath))
{
// Your code to save the file
}
I can guess that there is similarity in the name of the image file
try putting it under a different name
like
string filepath = # "images / blabla or AI.jpg";
Use this
string filepath= Application.StartupPath + "\images\image1.jpg";
bitmapImage.Save(filepath,System.Drawing.Imaging.ImageFormat.Jpeg);

how to display image using imageurl in C#

if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//string path = Server.MapPath(#"~\\"+Session["parentfolder"].ToString() +"\\"+ Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName);
string root = Server.MapPath("~");
string path = Path.GetDirectoryName(root);
string path1 = Path.GetDirectoryName(path);
string rootfolder = Path.GetDirectoryName(path1);
string imagepath = rootfolder + Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName;
FileUpload1.SaveAs(imagepath);
//objBAL.SaveImage("Image", Session["brandname"].ToString(), Seasonfolders.SelectedItem.Text, stylefolders.SelectedItem.Text, FileName, imagepath, Convert.ToInt32(Session["Empcode"]));
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
}
uploadedimage is ID for Image control. The path of imagepath is E:\Folder1\Folder2\Folder3\Images\1.png
The image is getting saved but I cannot able to display the uploaded image. Do I need to add anything in this line which is to display an image ..
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
Hosting websites or stuff on iis, does not work this way. There are a few concepts one needs to learn on that front, but the best place to start with is understand what is virtual directory.
One quote from the this page:
In IIS 7, each application must have a virtual directory, known as the
root virtual directory, and maps the application to the physical
directory that contains the application's content
So it means this is a directory where the application's "content" reside; it could be simple text files, images, etc, to complex server side pages like aspx or even classic asp, or php, etc. Now anything out of this directory is not accessible by the hosted web application.
Hence the path you intend to share doesn't work that way. There are a few options to handle this scenario.
In iis you could create a sub-virtual directory, and map its path to where your images are stored to the physical location where the images reside.
Provided your web application (when hosted on iis) has access to the path where the images reside, you can write code to read the file, and send the stream of bytes back so that your web page can render image properly.
2nd approach is usually implemented by a handler (ashx) via which you can pass the image name as query string argument, and return the bytes. Hence in short you do something like this:
uploadedImage.ImageUrl = "~/MyImageHandler.ashx?filename=foo.png" //in ur server code.
In the handler you write something like this:
public class MyImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
// Comment out these lines first:
// context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");
context.Response.ContentType = "image/png";
var filepath = #"E:\your_image_dir\" + Request.QueryString["filename"];
//Ensure you have permissions else the below line will throw exception.
context.Response.WriteFile(filepath);
}
public bool IsReusable {
get {
return false;
}
}
}
The image Url in your image should be like this
"~/"+ imagepath
Try removing Server.MapPath
Try this
Create Data Folder in your root directory
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string imagepath =Server.MapPath("~/Data/"+FileName);
FileUpload1.SaveAs(imagepath);
uploadedimage.ImageUrl="~/"+imagepath;
}

function has stopped working" Error in running the code

I have a windows form application which works with text file data sets that I tried to make portable (ie: To run the application from external hard drive or pen drive does not need to copy the data sets into the C:\ drive directly.
I changed
StreamReader fileitem = new StreamReader("c:\\dataset.txt");
into
StreamReader fileitem = new StreamReader("dataset.txt");
and copy the dataset into the exe file path (.../bin/debug)
But it shows an error "function has stopped working"!
Any idea?
Here's a sample of how you can get the absolute path to your executable file:
static public string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
Sample taken from this answer
If you implement this property you can then update your code to the following:
StreamReader fileitem = new StreamReader(AssemblyDirectory + "dataset.txt");

How to Remove ~ character from asp HyperLink

I have problem how to remove /~/ character from when I save file into database my problem is when they are no file into file upload controller I grape the NavigateUrl form asp hyper link and add to savePath to save it but I get exception it couldn't find the directory
Could not find a part of the path 'C:\inetpub\wwwroot\ideaPark\DesktopModules\ResourceModule\pdf_resources\~\DesktopModules\ResourceModule\pdf_resources\New Text Document.txt'.
//save pdf docs
String savePathPDF_Resouce = #"~/DesktopModules/ResourceModule/pdf_resources/";
String savePathPDF_Vocab = #"~/DesktopModules/ResourceModule/pdf_resources/";
if (fuPDFDoc.HasFile || fupdfVocabularyURL.HasFile)
{
String fileName = fuPDFDoc.FileName;
String fileName_Vocab = fupdfVocabularyURL.FileName;
savePathPDF_Resouce += fileName;
savePathPDF_Vocab += fileName_Vocab;
fuPDFDoc.SaveAs(Server.MapPath(savePathPDF_Resouce));
fupdfVocabularyURL.SaveAs(Server.MapPath(savePathPDF_Vocab));
}
else
if (!fuPDFDoc.HasFile || !fupdfVocabularyURL.HasFile)
{
savePathPDF_Resouce += hl_doc_res.NavigateUrl.ToString();
savePathPDF_Vocab += hl_doc_vocab.NavigateUrl.ToString();
fuPDFDoc.SaveAs(Server.MapPath(savePathPDF_Resouce));
fupdfVocabularyURL.SaveAs(Server.MapPath(savePathPDF_Vocab));
}
You could use something like this to get the path:
// root filesystem path for the application (C:\inetpub\wwwroot\ideaPark)
string virtualPathRoot = AppDomain.CurrentDomain.BaseDirectory;
// path relative to the application root (/DesktopModules/ResourceModule/pdf_resources/)
string relativePath = savePathPDF_Resouce.TrimStart("~");
// save here
string targetPath = Path.Combine(virtualPathRoot, relativePath);

Categories

Resources