C# program crash (.ico file) - c#

The program crashes if there's no .ico file inside the same folder. I have:
Added the MyIcon.ico file in the Application section, also 'embed manifest with default settings' is checked.
Made the .ico file as Embedded Resource (Build Action) in the .ico file properties.
Added this.Icon = new Icon("plat.ico"); in the Public form.
So... why is the application not booting? What gives?

The constructor for Icon you are using tries to read "plat.ico" as a filename, not from embedded resources.
If you want to load the Icon from resources, you will need to explicitly get a Stream from the resource, then pass that into the Icon's constructor.
This will likely be something similar to:
// Add using System.Reflection; at the top of your file...
this.Icon = new Icon(
Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace.plat.ico")
);
Alternatively, you can use the constructor overload that pulls directly from a resource, by name, instead of a filename:
this.Icon = new Icon(this.GetType(), "plat.ico");

I had the same problem in a windows form, where the icon could not be found even though it was in the same directory as the form.
notifyIcon1.Icon = new Icon("enabled.ico");
I looked at the .ico file's properties in VS2010 and saw that Copy to Output Directory was set to Do not copy. I changed it to Copy always and that did the trick.
Sometimes the simplest solution is the best solution.

You need to set the icon file's "Copy to Output" to "Copy Always" or "Copy if Newer".

You are invoking wrong constructor. Just use this:
this.Icon = new Icon(this.GetType(), "plat.ico");

Related

C#: opening a text file stored within the same project as the app

I managed to open a text file using an absolute path (in Visual Studio 2017) although if I change the location of my Solution folder the whole code would not work anymore as the actual physical path has changed and the code can not reference an existing location anymore.
I tried to create a text file within the same project and I would now like to open this file in my code, so if the location of the whole Solution changes the program can still work, would anyone be so kind to help me fix this issue?
I have also looked online for some different solution using code that references the current directory but I can't get my head around it as the current directory seems to be bin/debug and if I try to insert the file there the code doesn't recognize the location (also it doesn't look like a clean solution to me).
This is the code I am using so far in a WPF app, the whole purpose is to open the content of the text file containing countries listed line by line and to add them to a list box which will be displayed when a checkbox will be ticked.
private void listCountry_Initialized(object sender, EventArgs e)
{
listCountry.Visibility = Visibility.Hidden;
string path = "C:\\Users\\david\\source\\repos\\StudentRecord\\StudentRecordSystemMod\\StudentRecord\\country.txt";
if (File.Exists(path))
{
string[] myCountryFile = File.ReadAllLines(path);
foreach (var v in myCountryFile)
{
listCountry.Items.Add(v);
}
}
}
This is a great use case for OpenFileDialog Class.
Represents a common dialog box that allows a user to specify a filename for one or more files to open.
Here is the example of use, from the documentation.
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
}
Assuming C:\\Users\\david\\source\\repos\\StudentRecord\\StudentRecordSystemMod\\ is your project, and StudentRecord\\country.txt is a project folder and file in your project - you need change "Copy to Output Directory" to be "Always Copy" or "Copy If Newer" and "Build Action" to "Content" for the file in your project.
As you can see from the screenshot above, the folder structure for this content is created as well.
Then change your path assignment to be something like the following:
string path = string.Join(#"\", Application.ExecutablePath, #"StudentRecord\country.txt");
Clean and simple, place the file you want to open next to where the executable is generated, remember the executable path changes depending to if your project is in Debug or Release build mode. Now set:
string path = "country.txt";
By only providing a filename, the file is looked for in the same folder as the executable. Just remember that when you move the executable you must also move the file to the same place, but if you move the entire project folder then you're already set.
However, if you want to keep your file in a fixed location regardless of where you have your executable and/or VS project files, then the simplest path for it is:
string path = "C:\\country.txt";
This is an absolute path, but it's quite simple and very robust to changes, you would have to change the drive letter to break it and if C: is where your operating system files are then you probably won't do that.
If you don't like to have your files around in your root, you can always have a path like this:
string path = "C:\\ProjectNameFiles\\country.txt";
Or if you prefer to maintain a hierarchy of projects then you can use:
string path = "C:\\MyProjectsFiles\\ProjectName\\country.txt";
With this, every project can have a directory for the files it needs to open. These are all absolute paths, but are notably simpler than the one you posted, and they have a more fixed and organized structure.

Creating an executable file with an icon from another assembly

I'm looking for a way to take an icon from an executable, and create a new executable (using CSharpCodeProvider) that uses this icon.
The first part is easy, I do it using:
Icon icon = Icon.ExtractAssociatedIcon(path);
The problems come when I want to "attach" the icon. I tried using:
compilerParameters.CompilerOptions = #"/win32icon:"
But this solution requires the icon to be written in a file and I'd like to avoid that (one of the reason being it's such a mess to save an icon with more than 16 colors...).
Is it possible to use the System.Drawing.Icon object in memory directly?
EDIT: Just to be clear, I'm trying to obtain a code that can compile C# code into an executable. This executable will have an icon that is only hold in memory (as an Icon object) and not in a file (as a .ico file).
Use the IconLibrary to save Icon
Icon icon = Icon.ExtractAssociatedIcon(#"C:\Windows\System32\notepad.exe");
MultiIcon mIcon = new MultiIcon();
SingleIcon sIcon = mIcon.Add("notepad");
sIcon.CreateFrom(icon.ToBitmap(), IconOutputFormat.Vista);
sIcon.Save(#"c:\notepad.ico");
And use that for CompilerOptions
More information
https://msdn.microsoft.com/en-us/library/2aaxe43f.aspx
Solution :
In case anyone is looking to do the same thing, here is a method that brought the expected result (icon extracting with correct graphic quality).
I use Tsuda Kageyu IconExtractor in order to get the icon I want and convert it to Bitmap with the transparency.
Then I use the IconLibrary suggested by #mohsen to write in icon as a .ico file and then embed it with the CompilerOptions.

Having Trouble Accessing an Embedded Resource [duplicate]

I have a game application in Visual Studio 2012 C#. I have all the .png images I am using in the Resources file of the project.
Have you any idea why I can access all the files but one by using Properties.Resources?
I checked the full filePath and it's set to the resources folder. And it's added in the program as I did Add -> Existing Item and added the image.
It looks just like the other images. I have no idea why it's not loading. I need this since I need to send a .exe by email to my lecturer and without this image the project is nothing!
I added this in the resource file
internal static System.Drawing.Bitmap grid_fw {
get
{
object obj = ResourceManager.GetObject("grid.fw", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
and although now grid is available, it is returning null :/
Found from: Properties.Resources the icon name does not appear in the intellisense
You also need to add the icon to the Resources.resx file. Open it in
Visual Studio and drag your icon into the Icons menu of the resx and
it will become available.
Also, see Adding and Editing Resources (Visual C#)
You can get a reference to the image the following way:
Image myImage = Resources.yourImage;
If you want to make a copy of the image, you'll need to do the following:
Bitmap bmp = new Bitmap(Resources.yourImage);
Don't forget to dispose of bmp when you're done with it. If you don't know the name of the resource image at compile-time, you can use a resource manager:
ResourceManager rm = Resources.ResourceManager;
Bitmap yourImage = (Bitmap)rm.GetObject("yourImage");
The benefit of the ResourceManager is that you can use it where Resources.myImage would normally be out of scope, or where you want to dynamically access resources. Additionally, this works for sounds, config files, etc.

Accessing Resources at Runtime

I have an XML file included as part of my Silverlight 4.0 project that I'd like to access at runtime. I have the file saved in a directory named Resources with the Build Action set to "Content" and the Copy to Output Directory set to "Do not copy". If I decompress the XAP file, I see the XML file in the location I expect it to be, but I'm not sure how to reference it from code. I currently have the following:
Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(#"/AssemblyName;component/Resources/MyFile.xml")
Unfortunately, stream is null after running the code above. In addition to the path mentioned above, I've tried "/Resources/MyFile.xml", "/MyFile.xml" and "MyFile.xml", but they all experience the same behavior.
What is the correct way to access an XML file embedded as a resource in a Silverlight application?
A resource with build action "Content" just gets embedded into the xap file, with the same relative directory structure as the application. It does not get embedded as a resource in the assembly.
When set to build action "Content", you should be able to just load the file using something like (or whatever suits your needs):
XElement.Load(<relative directory>/<file>)
The method you're using currently (using a resource stream) is for embedded resources (which have their build action set to "Resource"). And for those, although I haven't tried yet if your method works, usually you'll get the resources using
Application.GetResourceStream
I have used the code snip below to get access to drawables. Not sure it's completely relevant, but hoping this will give you a hint one way or another ...
Resources res = getResources();
spec = tabHost.newTabSpec("groups").setIndicator("Groups", res.getDrawable(R.drawable.ic_tab_groups)).setContent(intent);
As was mentioned by Willem van Rumpt, "content" resources are not usual resources (they aren't stored in assembly). I've checked out this article and could't found at all that you could reference resource, marked as "content" from other assembly.
So, you have two options:
Define XML as embedded resource
Define XML as resource
In first case stream request looks like:
var a = Assembly.Load("AssemblyName");
var s = a.GetManifestResourceStream(#"DefaultNamespace.Resources.XMLFile2.xml");
In second case:
var a = Assembly.Load("AssemblyName");
var rm = new ResourceManager("AssemblyName.g", a);
using (var set = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true))
{
var ums = (UnmanagedMemoryStream)set.GetObject(#"Resources/XMLFile1.xml", true);
}
Hope this helps.

Using Custom Cursor WinForms

Is there a way to use a custom cursor in winforms?
There seems to be no option. But when I try to manually add a cursor as a resource, then call it from code, it says that it cannot convert from type byte[] to Cursor.
Adding custom icon to cursor in C# :
Add Icon file to Project resources (ex : Processing.ico)
And in properties window of image switch "Build Action" to "Embedded"
Cursor cur = new Cursor(Properties.Resources.**Imagename**.Handle);
this.Cursor = cur;
Ex:
Cursor cur = new Cursor(Properties.Resources.Processing.Handle);
this.Cursor = cur;
From the MSDN documentation on the Cursor class (with minor corrections):
// The following generates a cursor from an embedded resource.
// To add a custom cursor, create or use an existing 16x16 bitmap
// 1. Add a new cursor file to your project:
// File->Add New Item->Local Project Items->Cursor File
// 2. Select 16x16 image type:
// Image->Current Icon Image Types->16x16
// --- To make the custom cursor an embedded resource ---
// In Visual Studio:
// 1. Select the cursor file in the Solution Explorer
// 2. Choose View->Properties.
// 3. In the properties window switch "Build Action" to "Embedded"
// On the command line:
// Add the following flag:
// /res:CursorFileName.Cur,Namespace.CursorFileName.Cur
//
// Where "Namespace" is the namespace in which you want to use
// the cursor and "CursorFileName.Cur" is the cursor filename.
// The following line uses the namespace from the passed-in type
// and looks for CustomCursor.MyCursor.Cur in the assemblies manifest.
// NOTE: The cursor name is case sensitive.
this.Cursor = new Cursor(GetType(), "MyCursor.Cur");
I've used the LoadCursorFromFile() method from User32.dll. There are plenty of samples for this on the web.
OR
The ctor for the Cursor type also has a IO.Stream overload. Load your byte[] into a MemoryStream and feed that to the new Cursor.
After adding the file to the resources, in the properties window of the image: switch Build Action to Embedded Resource and write in your code:
"name of control".Cursor = new System.Windows.Forms.Cursor(Properties.Resources."name of image".Handle);
Convert your cursor from any format to ico using convertico.com(It is the best way of doing this), copy your cursor to your project's debug folder using file explorer and write this code(C#):
this.Cursor = new Cursor("default.ico");
I had the same problem for a while. So, as far as I understood, these are 2 ways to solving that issue:
Putting cursor .ico file into the Resources
Getting cursor from .ico file without putting it the resources
First case:
After putting to the resources you can just add .Handle after the name of resource while getting it. For instance:
this.Cursor = new Cursor(Properties.Resources.YourResource.Handle);
Second case:
This one looks a bit easier, but before that you should add your .ico file to project and in properties of that file you should set Always copy for file to be copied automatically to the execution folder. After that you can easyly use this:
this.Cursor = new Cursor("YourIcon.ico");
To my mind, using the resources for permanent files like cursor icons is the best practice, so the used the first one.

Categories

Resources