C# - Loading images into a imagelist and listview - c#

I have gotten a program Im working on to load some pictures and display them within a listview after using a openfiledialog. What I am looking to do now is take this one step further and auto-load the images from a directory 'icons' within the application directory. Im not too sure how to go about it, So Im going to paste my current code here, and work it from there...
private void loadImageLibraryToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (openFileDialog1.FileNames != null)
{
for (int i = 0; i < openFileDialog1.FileNames.Length; i++)
{
addImage(openFileDialog1.FileNames[i]);
}
}
else
addImage(openFileDialog1.FileName);
}
}
private void addImage(string imageToLoad)
{
if (imageToLoad != "")
{
imageList1.Images.Add(Image.FromFile(imageToLoad));
listView1.BeginUpdate();
listView1.Items.Add(imageToLoad, baseValue++);
listView1.EndUpdate();
}
}
Edit to Clarify: The code provided shows how to load and show the images in a listview control. What Im looking to do now is upon starting the app, load the images automatically from a folder in the programs directory, and then display them in the listview.

Off the top of my head with no IDE so there may be mistakes! try this
var files = System.IO.Directory.GetFiles(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "\\icons")
files will be an array of strings containing all the files in the directory which you can then loop as you have above using the array
openFileDialog1.FileNames
The \ may not be required before icons, I can't remember if GetDirectoryName drops the trailing \ from the path or not.
you can also pass a filter to GetFiles to only return certain file types.
HTH
EDIT: I have edited the code above to use
System.Windows.Forms.Application.ExecutablePath
rather than
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
On testing the code now I have access to an IDE it seems the CodeBase property prepends the path with file:/// which caused my IDE to blow up with an error saying
URI formats are not supported
the code now works in my IDE, You need to make sure your icons Directory is in the same directory as your executable so in my case ....bin\debug\
Give this a try and if it still fails let me know!

Related

GDI + Generic error only on specific case [C#]

tldr:
I have one function that draws image that I save later.
I can save file in every possible scenario except when I drag image to exe while that image is not in the same folder. Dragged image just feeds string path to the function.
/tldr
I have a function that draws image in Picture Box on Windows Forms.
This function accepts string - path, and then processes the data.
When user drops picture on form, I send path from dropped file to my function and it draws file just fine.
Then I hit save button which contains next code :
Bitmap tmpOutputSave = new Bitmap(pbOutput.Image);
tmpOutputSave.Save("Generisano\\Image" + tmpDate + ".png", System.Drawing.Imaging.ImageFormat.Png);
And I save the image.
Everything works fine.
If I open my application in D:\some_path\MyApplication\myapp.exe and I drag image file from Desktop, I will see the image in picturebox, and when I hit save - everything works fine.
If I drag image file from same folder to myapp.exe, and hit save - everything works fine too, and I can see the image in picturebox.
However, in this second case, if I drag image from any other folder to myapp.exe, image will load as well but when I try to save I will get "Generic error in GDI+".
Code that I'm using to get path from dragged file to exe is :
program.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args));
}
}
form1.cs
public Form1(string[] args) {
InitializeComponent();
sablon = new Sablon(this);
LoadSettings();
pbOutput.MouseWheel += pbOutput_MouseWheel;
if (args.Count() > 0) {
try
{
imgPath = args[0];
pbOutput.Image = Crtaj.Sliku(imgPath);
hadFirstArgument = true;
}
catch (Exception e)
{
MessageBox.Show("Error : " + e.Message);
}
}
}
Notes : Crtaj.Sliku is : Class : Crtaj, with function Sliku - which accepts string to draw image.
So to sum up :
- It's the same function for all cases
- Dragging on form from any location works fine
- Dragging on exe from same folder works fine
- Dragging on exe from another folder doesn't work
- Paths are same in all cases, image is same in all cases
Only difference is that I try to drag and drop file from another folder on exe (no problem if I do it on form, even though code and paths are the same).
I saw many topics about this, but I didn't really see specific issue related to mine, I'm sorry if I oversaw something.
What could be the problem ?
I'm sure that it's not illegal characters or file location - because I format characters before saving, I'm sure that folder exists and paths are the same too.
Thank you!
Can you try it using an absolute path? Like setting the savefile location to somewhere like;
C:\Temp\Test.png
Or somewhere that you know exists. If you're generating the save path (even if it's with the same code), the resulting folders might be different in your two cases, and it may fail to save the file because of that. I remember losing some hair because of that a few years ago. If that happens to be the case, you'll only need to look into why the generated path points to an incorrect location.

C# Drag Drop to desktop, and get the directory

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
string[] files = new string[] { #"C:\directory\of\file\to\copy.txt" };
this.DoDragDrop(new DataObject(DataFormats.FileDrop,files), DragDropEffects.Copy);
}
This is the code that i used.
Well, it works well, but want to get the directory of the copied file.
How can I do this?
Using that the static Path class of System.IO,you can extract the path of directory
Path.GetDirectoryName(#"C:\Users\JNK\Desktop\2136D.png");
All you got is the return value of DoDragDrop() to see if the drop actually happened. What the receiving app did with the file is something you cannot find out. Could be anything, including not copying the file at all. A random example is only opening the file in a text editor, the behavior of VS and Notepad.
Note how the example you gave only drags from the desktop, not to the desktop. Use FileBrowserDialog if you need to know where the user wants to copy a file.

C# WPF - Printing all files in directory that has ".xml" format - "could not find part of the path c#"

First of all - i googled the problem, and nothing good related seemed to come up.
Also it will probably seem to you that this question is a newbie one (and i must say i never had this problem when printing files in a directory.
I am pretty new to WPF in C#.
so..
I am having problems to Print all files in directory that has ".xml" format
Here is my code to print the files in a directory (I am not talking about Recursive dirs and files print):
private void Load_ToolboxItems(string dirPath, string os, string version)
{
try
{
foreach (string command in Directory.GetFiles(dirPath, "*.xml"))
{
//load commands by OS compatibility
MessageBox.Show(command);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is my window load event:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Combined " + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName), #"\data\Windows\xp\"));
MessageBox.Show(System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName));
Load_ToolboxItems(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName), #"\data\Windows\xp\"), "Windows", "XP");
}
Those are the outputs i get when running the program:
1st messagebox- "Combined \data\Windows\xp\"
2nd messagebox-
C:\Users\Din\Din\Programming\Webs\Ended Projects\LogicalArm\Products\Visual Command Line\Visual_Command_Line-wpf_net3.5c_vs2010\Visual_Command_Line\bin\Release
3rd messagebox- "could not find part of the path 'C:\data\Windows\xp'."
This is where the exe starts from:
C:\Users\Din\Din\Programming\Webs\Ended Projects\LogicalArm\Products\Visual Command Line\Visual_Command_Line-wpf_net3.5c_vs2010\Visual_Command_Line\bin\Release
foreach (String file in Directory.GetFiles(dirPath))
{
if (Path.GetExtension(file) == ".xml")
MessageBox.Show(file);
}
Not sure if your underlying issues is you are not getting the exact path you want, however the above should give you what you want from a listing of XML files stance.
Remove the \ from \data\windows\xp (the first \ that is). Also be careful because your path is getting long. There is a 260 character limit.
Path.Combine() know the directory separator character to use, so when you use it, the second parameter should not start with a .
huh,
it always happens to me..
five minutes after i ask a question and after a long search i some-how find the problem myself..
I had problem with the path -_-
thanks for trying to help by the way

Program fails to load image from relative path on drag-drop file open

I have a program I have written in C#, which loads an image with Image.FromFile, and it loads the image successfully every time. However, when you drag and drop another file on the executable, like you are giving the program the command line argument of the file, and the file is not in the same folder as the executable, the program crashes because it says the path to the file does not exist, even though it does.
I think that by dropping a file on the executable, it's changing the path it's loading images from somehow. How can I fix this problem?
Your program would be started with a different Environment.CurrentDirectory. Always make sure you load files with an absolute path name (i.e. don't use Image.FromFile("blah.jpg")).
To get the absolute path to a file that's stored in the same directory as your EXE, you could use Application.StartupPath for example. Or Assembly.GetEntryAssembly().Location if you don't use Windows Forms.
It depends on how you are initiating the file drag outside of your application. If you click and drag a file from Windows Explorer, the full absolute path name is included in the drop. In this case the following code shows the filename and performs a drop of the file's contents into a textbox:
private void textBox1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
var objPaths = (string[])(e.Data.GetData(DataFormats.FileDrop));
if (objPaths != null && objPaths.Length > 0 && File.Exists(objPaths[0]))
{
MessageBox.Show(string.Format("Filename: {0}", objPaths[0]));
using (TextReader tr = new StreamReader(objPaths[0]))
textBox1.Text = tr.ReadToEnd();
}
}
}
So let us know more about your drag source. Most likely you will have to modify your source to drag the absolute path, or somehow determine the full path from the relative path in the drag data.
Also, your program should never crash due to bad data. Either check for the required conditions, or use a try/catch block around the necessary code.

How to retrieve Image from Resources folder of the project in C#

i Have some images in resources folder in my project but i want to change the picture box from these resource files of the project
Consider using Properties.Resources.yourImage
Properties.Resources contains everything that you've added as a resource (see your project properties, resources tab)
Other than that, if you embed the images as resource in your project, you can get at them by calling GetManifestResourceStream on the assembly that you've embedded the images in, something like
Stream imgStream =
Assembly.GetExecutingAssembly().GetManifestResourceStream(
"YourNamespace.resources.ImageName.bmp");
pictureBox.Image = new Bitmap(imgStream);
Don't forget to mark the image as an embedded resource! (You'll need to set the build action for the image in its properties window)
If you're finding that you keep getting back null from GetManifestResourceStream, you may be giving the wrong name. (It can be hard to get the names right) Call GetManifestResourceNames on the assembly; that will give you back all the resource names, and you can find the one in the list that you need.
string img = null;
private void btnShow_Click(object sender, EventArgs e)
{
string imgName;
img = textBox1.Text;
imgName = "images/" + img + ".jpg";
if (imgName == null)
{
MessageBox.Show("no photo");
}
else if (imgName != null)
{
this.picBox1.Image = Image.FromFile("images/" + img + ".jpg");
}
}
Below is the Code to Fetch Image From Resources Folder. Normally we keep images in Resources Folder. but Sometime we have image name only with us. in that case you can Access images from Resources Folder using Image Name only.
Below Code will Demonstrate about it.
private System.Resources.ResourceManager RM = new System.Resources.ResourceManager("YourAppliacationNameSpace.Properties.Resources", typeof(Resources).Assembly);
PbResultImage.Image = (Image)RM.GetObject(YourPictureName);
YourAppliacationNameSpace means name of your Application.
YourPictureName means the Picture you Want to access from Resources Folder. but Picture name must be without Extension e.g. (PNG, GIF, JPEG etc)
hope i will be beneficial to some one.
Thank you.
Right click on the project. Go to Resources tab. Select the existing option and add the image.
Now access in the code by
Image = Properties.Resources.ImageName
Worked for me:
(Bitmap) Properties.Resources.ResourceManager.GetObject("ImageName");
this works for your control too, if you need to call your control by a string or concatenated reference.
Just call the control type first (in this case, a picturebox). Assume i=some number and d=some string:
var i = <some number>;
var d = <some string>;
((PictureBox)this.Controls["pictureBox" + i.ToString()]).Image = (Image)Properties.Resources.ResourceManager.GetObject("dice" + d);
Now it's Possible
pictureBox.Image = Properties.Resources.yourImagename;

Categories

Resources