How to get icon image - c#

I want to make same Window File explorer.
but I don't know how to get file default Icon image.
If I can get file default image(Icon), I would like to add to the listview.
my code is as below
private void AddFiles(string strPath)
{
lv_local.BeginUpdate();
lv_local.Items.Clear();
iFiles = 0;
try
{
DirectoryInfo di = new DirectoryInfo(strPath + "\\");
FileInfo[] theFiles = di.GetFiles();
foreach (FileInfo theFile in theFiles)
{
iFiles++;
ListViewItem lvItem = new ListViewItem(theFile.Name);
lvItem.SubItems.Add(String.Format("{0:N0}", theFile.Length) + "KB");
lvItem.SubItems.Add(theFile.Extension);
lvItem.SubItems.Add(theFile.LastWriteTime.ToShortDateString());
lvItem.ImageIndex = 4;
// I want to put an image that was read default image
lv_local.Items.Add(lvItem);
}
}
catch (Exception Exc)
{
}
lv_local.EndUpdate();
}

Create ImageList and add icons
var imageList = new ImageList();
imageList.Images.Add("IconKey", icon);
Assign the ImageList to ListView
listView.LargeImageList = imageList;
Assign icon for the list view item
listViewItem.ImageKey = "itemImageKey";
or listViewItem.ImageIndex = 1;

Related

C#: Unable to assign Image to PictureBox image source path from text file in winforms

I'm trying to display image in a PictureBox dynamically. Image source is stored in a text file. When reading the image path from the file it keep showing image error symbol. When I include the path in the code it works.
Text file line sample
F01,Nasi Lemak,RM 2,#"Food\NasiLemak.jpg"
public void readData()
{
try
{
int i = 0;
foreach (string line in File.ReadAllLines("food.txt"))
{
string[] parts = line.Split(',');
foreach (string part in parts)
{
Console.WriteLine("{0}:{1}", i, part);
{
Label LblFId = new Label();
{
//LblFId.AutoSize = true;
LblFId.Size = new System.Drawing.Size(70, 20);
}
Label LblFName = new Label();
{
LblFName.Size = new System.Drawing.Size(70, 20);
}
Label LblFPrice = new Label();
{
LblFPrice.Size = new System.Drawing.Size(70, 20);
}
PictureBox foodPicBox = new PictureBox();
{
foodPicBox.Size = new System.Drawing.Size(200, 200);
foodPicBox.SizeMode = PictureBoxSizeMode.StretchImage;
foodPicBox.BorderStyle = BorderStyle.Fixed3D;
}
Panel fPanel = new Panel();
LblFId.Text = parts[0];
LblFName.Text = parts[1];
LblFPrice.Text = parts[2];
foodPicBox.ImageLocation = parts[3];
fPanel.Controls.Add(LblFId);
fPanel.Controls.Add(LblFName);
fPanel.Controls.Add(LblFPrice);
fPanel.Controls.Add(foodPicBox);
foodFlow.Controls.Add(fPanel);
}
}
i++;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
The problem is in the path from the text file
#"Food\NasiLemak.jpg"
This should be saved like without the # and the "
Food\NasiLemak.jpg
Or you should write more code to remove those symbols like this
foodPicBox.ImageLocation = parts[3].Replace("#", "").Replace("\"", "");
This will remove the samples and your problem would be solved.
You need also to close foreach statment at this point
foreach (string part in parts)
{Console.WriteLine("{0}:{1}", i, part);}

Listview puts the same images in every group

My listview should make a group for every directory on a specified path, and add the pictures from each directory to the group that was created for it; but instead it adds the pictures from the last directory to each group.
Any ideas how can i solve this problem?
Thank you!
private void Form2_Load(object sender, EventArgs e)
{
string path = #"C:\pics\";
string[] tabs_needed = System.IO.Directory.GetDirectories(path);
foreach (string folder in tabs_needed)
{
FileInfo f = new FileInfo(folder);
listBox1.Items.Add(f.Name);
TabPage ghhk = new TabPage(f.Name);
tabControl1.Controls.Add(ghhk);
ListView listView1 = new ListView();
ghhk.Controls.Add(listView1);
listView1.Dock = DockStyle.Fill;
string new_path = path + f.Name;
string[] groups_needed =System.IO.Directory.GetDirectories(new_path);
foreach (string ufolder in groups_needed)
{
FileInfo uf = new FileInfo(ufolder);
string f_path = String.Concat(new_path + #"\" + uf.Name + #"\");
DirectoryInfo dir = new DirectoryInfo(f_path);
ImageList imagelist = new ImageList();
foreach (FileInfo file in dir.GetFiles())
{
try
{
imagelist.Images.Add(Image.FromFile(file.FullName));
}
catch
{
}
}
imagelist.ImageSize = new Size(32, 32);
listView1.View = View.LargeIcon;
ListViewGroup gr1 = new ListViewGroup(uf.Name);
listView1.Groups.Add(gr1);
string tpath = String.Concat(f_path, "gf.txt");
for (int counter = 0; counter < imagelist.Images.Count; counter++)
{
ListViewItem item = new ListViewItem();
item.Text = File.ReadAllLines(tpath).Skip(counter).Take(1).First();
item.ImageIndex = counter;
item.Group = gr1;
listView1.Items.Add(item);
}
listView1.LargeImageList = imagelist;
}
This is happening because you are instantiating the ImageList each time in the foreach loop. When you assign the imagelist finally to listView1.LargeImageList, it is only the final imagelist instance that gets attached.
You will need to move the instantiation out of the foreach loop
ImageList imagelist = new ImageList();
foreach (string ufolder in groups_needed)
{
...
}
You may also need to change the logic for your ImageIndex to get this working, now that the ImageList is out of the loop.
You should replace
listView1.LargeImageList = imagelist;
with
listView1.LargeImageList.Images.AddRange(imagelist.Images.Cast<System.Drawing.Image>().ToArray())
Because you are overwriting image list at each cycle.

Trying to show pictures from folder in winform

I am trying to load pictures that are in a certain folder (camera) into my application using a listview and pictureList. For some reason the files are loaded but do not appear in the listview.
This is the code I have so far:
try
{
listView1.View = View.LargeIcon;
imageList1.ImageSize = new Size(32, 32);
listView1.LargeImageList = imageList1;
DirectoryInfo directory = new DirectoryInfo(#"C:\");
FileInfo[] Archives = directory.GetFiles("*.JPG");
foreach (FileInfo fileinfo in Archives)
{
imageList1.Images.Add(Image.FromFile(fileinfo.FullName));
}
listView1.Update();
MessageBox.Show("I found " + imageList1.Images.Count.ToString() + " images!");
}
catch
{
MessageBox.Show("Something went wrong!");
}
Note that the messagebox is showing me the correct number of files, so I suppose I have some part right. Any clues what might be wrong?

Add image from local system to listbox

I have a listbox and i want to update my listbox with all the logical drives. I want to show all the images in a parent and child format. I am using this code
string[] path = System.IO.Directory.GetLogicalDrives();
foreach (string directories in path)
{
Bitmap bitimg = null;
DirectoryInfo dinfo = new DirectoryInfo(directories);
FileInfo[] Files = dinfo.GetFiles("*.jpg");
for (int i = 0; i < Files.Count(); i++)
{
string fileName = Files[i].FullName;
Uri uri = new Uri(fileName, UriKind.Relative);
BitmapImage bitmap=new BitmapImage(uri);
Image img = new Image();
img.Source(bitmap);
listBox1.Items.Add(img);
}
}
But i am getting error as
Cannot create an instance of the abstract class or interface 'System.Drawing.Image'

Why can I only write ONE item in my Resource.resx file?

I thought I am writing 10 file extensions and their related Icons as Bitmap into a resource file within a for loop. The odd thing is that only the last file extension with its Icon is written into the Resource.resx file. Somehow the next file extension in the loop is overwriting the previous one, but WHY ? I thought a resource is sort of a dictionary with key/value pair where I can add as much as I want just as I do in the Resource designer...
What do I wrong?
My code:
private void AddDocument()
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = true;
DialogResult result = fileDialog.ShowDialog();
if (result == DialogResult.OK)
{
for (int i = 0; i < fileDialog.FileNames.Length; i++)
{
string absoluteFilePath = fileDialog.FileNames.GetValue(i).ToString();
byte[] file = File.ReadAllBytes(absoluteFilePath);
String fileExtension = Path.GetExtension(absoluteFilePath);
Bitmap gdiImage;
Document doc = new Document();
doc.DocumentData = file;
doc.DocumentName = fileDialog.SafeFileNames.GetValue(i).ToString();
if (TryIsFileExtensionExisting(fileExtension, out gdiImage))
{
// Filetype was saved before => Convert GDI Bitmap to wpf BitmapImage
doc.DocumentTypeImage = gdiImage.ConvertGDIImageToWPFBitmapImage();
}
else
{
BitmapImage wpfImage;
// Filetype is new => get Bitmap out of the Icon
Icon icon = IconFromFilePath(absoluteFilePath);
Bitmap bitmap = icon.ToBitmap();
wpfImage = bitmap.ConvertGDIImageToWPFBitmapImage();
doc.DocumentTypeImage = wpfImage;
// Save bitmap to resource
using (ResXResourceWriter writer = new ResXResourceWriter("TBM.Resource"))
{
writer.AddResource(fileExtension, bitmap);
writer.Generate();
}
}
DocumentList.Add(doc);
}
_documentService.AddDocumentsToPeriod(DocumentList, _parentId);
}
}
private bool TryIsFileExtensionExisting(String fileExtension, out Bitmap wpfImage)
{
DictionaryEntry entry;
using (ResXResourceReader reader = new ResXResourceReader ("TBM.Resource"))
{
entry = reader.Cast<DictionaryEntry>()
.Where(x => x.Key.ToString()
.Equals(fileExtension, StringComparison.CurrentCultureIgnoreCase))
.FirstOrDefault();
};
wpfImage = entry.Value as Bitmap;
return entry.Key != null;
}
private Icon IconFromFilePath(string filePath)
{
Icon result = null;
try
{
result = Icon.ExtractAssociatedIcon(filePath);
//'# swallow and return nothing. You could supply a default Icon here as well
}
catch
{
}
return result;
}
The problem is here:
using (ResXResourceWriter writer = new ResXResourceWriter("TBM.Resource"))
{
writer.AddResource(fileExtension, bitmap);
writer.Generate();
}
Each time you create a new writer object and write to it. But you don't have the creation of the writer object read from the old file. So you overwrite every time. You should be able to use a different constructor and solve your problem.
http://msdn.microsoft.com/en-us/library/system.resources.resxresourcewriter.aspx

Categories

Resources