Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

c# - Save Icon File To Hard Drive

I know that this must be incredibly easy - It's unbelievable how long I have searched for an answer to this question based on how simple it is in VB6. I simply want to extract an Icon from an EXE File using Icon.ExtractAssociatedIcon, and then save this icon file to my hard drive.

So, here is what I have, and I will also show you what I have tried so you don't think I'm being lazy.

OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();

string s = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"IconData.ico";

Icon ico = Icon.ExtractAssociatedIcon(ofd.FileName);
Bitmap bmp = ico.ToBitmap();

bmp.Save(s, System.Drawing.Imaging.ImageFormat.Icon);

The above code just makes a file called "IconData.ico" on my desktop which is 0 bytes in length. Again, I am sure this must be incredibly easy to do, but for the life of my I can't figure it out.

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will get better results if you save the icon without first converting to a bitmap. This is because an "Icon" can contain multiple sizes whereas a bitmap is a single size chosen during the conversion.

The Icon class does not have a save to file method, but it does have a save to FileStream method, so you can save it like this:

        string s = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"IconData.ico";
        using (FileStream fs = new FileStream(s, FileMode.Create))
            ico.Save(fs);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...