我已经知道如何通过P/调用SHGetFileInfo来获取特定路径的文件系统相关图标。但这需要一条实际的道路。另外,它仅返回一个图标。
我想知道的是两方面的。
SHGetFileInfo的“虚拟”路径,而忘记拥有两种状态?
最佳答案
是的你可以。
Disclaimer (TL,DR) :
Don't get mad at me for the length of this answer. 98% of it is just plain enumeration code you only have to copy paste (I just like having everything at the same place and time)
DestroyIcon(handle)的使用没有做过任何改变(这也会使您的图标缩小为零尺寸的0x0图标),而您应该在代码的其他地方使用该图标。 ..... Plus, it only returns a single icon...
SHSTOCKICONID结构SHGetStockIconInfo(...) Icon icon = Icon.FromHandle(handle)
// And here is where you don't really know how to destroy the handle...
CAUTION !!!
The API and some enum values doesn't work on some platforms. Simply put, everything before Windows Vista has little to no support at all. Furthermore, almost everything is for Desktop Applications only ! By the way, things may not work on Windows CE.Windows 7 and above has extended capabilities that are not covered by this answer.
Known alternative to API calls : WPF and VectorIcons. Not covered here.
using System.Runtime.InteropServices; // [DllImport()], [MarshalAs()]
using System.Runtime.CompilerServices // [Extension()]
DestroyIcon() 方法。/// <summary>
/// Destroys an icon and frees any memory the icon occupied.
/// </summary>
/// <param name="hIcon">A handle to the icon to be destroyed. The icon must not be in use.</param>
/// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.</returns>
/// <remarks>To get extended error information, call GetLastError.</remarks>
[DllImport("user32.dll", EntryPoint = "DestroyIcon", SetLastError = true)]
private static extern bool DestroyIcon(IntPtr hIcon);
Shell32声明(由PInvoke提供,添加了XML注释):/// <summary>
/// Retrieves information about a stock icon.
/// </summary>
/// <param name="siid">One of the values from the SHSTOCKICONID enumeration that specifies which icon should be retrieved.</param>
/// <param name="uFlags">A combination of zero or more of the following flags that specify which information is requested.</param>
/// <param name="psii">A pointer to a SHSTOCKICONINFO structure. When this function is called, the cbSize member of this structure needs to be set to the size of the SHSTOCKICONINFO structure. When this function returns, contains a pointer to a SHSTOCKICONINFO structure that contains the requested information.</param>
/// <returns>If this function succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code.</returns>
/// <remarks>If this function returns an icon handle in the hIcon member of the SHSTOCKICONINFO structure pointed to by psii, you are responsible for freeing the icon with DestroyIcon when you no longer need it.</remarks>
[DllImport("Shell32.dll", SetLastError = false)]
private static extern Int32 SHGetStockIconInfo(SHSTOCKICONID siid, SHGSI uFlags, ref SHSTOCKICONINFO psii);
SHSTOCKICONINFO结构的样子(添加了XML注释):/// <summary>
/// Receives information used to retrieve a stock Shell icon. This structure is used in a call SHGetStockIconInfo.
/// </summary>
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SHSTOCKICONINFO
{
/// <summary>
/// The size of this structure, in bytes.
/// </summary>
public UInt32 cbSize;
/// <summary>
/// When SHGetStockIconInfo is called with the SHGSI_ICON flag, this member receives a handle to the icon.
/// </summary>
public IntPtr hIcon;
/// <summary>
/// When SHGetStockIconInfo is called with the SHGSI_SYSICONINDEX flag, this member receives the index of the image in the system icon cache.
/// </summary>
public Int32 iSysIconIndex;
/// <summary>
/// When SHGetStockIconInfo is called with the SHGSI_ICONLOCATION flag, this member receives the index of the icon in the resource whose path is received in szPath.
/// </summary>
public Int32 iIcon;
/// <summary>
/// When SHGetStockIconInfo is called with the SHGSI_ICONLOCATION flag, this member receives the path of the resource that contains the icon. The index of the icon within the resource is received in iIcon.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
public string szPath;
}
MAX_PATH结构中的 SHSTOCKICONINFO ,所以它是:const Int32 MAX_PATH = 260;
SHGSI 是一个枚举,用于定义要与调用SHGetStockIconInfo()一起提交的选项/// <summary>
/// UInt Enumeration with Flags that specify which information is requested.
/// </summary>
[Flags()]
public enum SHGSI : UInt32
{
/// <summary>
/// The szPath and iIcon members of the SHSTOCKICONINFO structure receive the path and icon index of the requested icon, in a format suitable for passing to the ExtractIcon function. The numerical value of this flag is zero, so you always get the icon location regardless of other flags.
/// </summary>
SHGSI_ICONLOCATION = 0,
/// <summary>
/// The hIcon member of the SHSTOCKICONINFO structure receives a handle to the specified icon.
/// </summary>
SHGSI_ICON = 0x100,
/// <summary>
/// The iSysImageImage member of the SHSTOCKICONINFO structure receives the index of the specified icon in the system imagelist.
/// </summary>
SHGSI_SYSICONINDEX = 0x4000,
/// <summary>
/// Modifies the SHGSI_ICON value by causing the function to add the link overlay to the file's icon.
/// </summary>
SHGSI_LINKOVERLAY = 0x8000,
/// <summary>
/// Modifies the SHGSI_ICON value by causing the function to blend the icon with the system highlight color.
/// </summary>
SHGSI_SELECTED = 0x10000,
/// <summary>
/// Modifies the SHGSI_ICON value by causing the function to retrieve the large version of the icon, as specified by the SM_CXICON and SM_CYICON system metrics.
/// </summary>
SHGSI_LARGEICON = 0x0,
/// <summary>
/// Modifies the SHGSI_ICON value by causing the function to retrieve the small version of the icon, as specified by the SM_CXSMICON and SM_CYSMICON system metrics.
/// </summary>
SHGSI_SMALLICON = 0x1,
/// <summary>
/// Modifies the SHGSI_LARGEICON or SHGSI_SMALLICON values by causing the function to retrieve the Shell-sized icons rather than the sizes specified by the system metrics.
/// </summary>
SHGSI_SHELLICONSIZE = 0x4
}
SHSTOCKICONID是一个包含很多值的枚举。希望您不会有那么头疼...:P-请坐一下这个Enumeration的MSDN constants,以了解图标的外观。/// <summary>
/// Used by SHGetStockIconInfo to identify which stock system icon to retrieve.
/// </summary>
/// <remarks>SIID_INVALID, with a value of -1, indicates an invalid SHSTOCKICONID value.</remarks>
public enum SHSTOCKICONID : UInt32
{
/// <summary>
/// Document of a type with no associated application.
/// </summary>
SIID_DOCNOASSOC = 0,
/// <summary>
/// Document of a type with an associated application.
/// </summary>
SIID_DOCASSOC = 1,
/// <summary>
/// Generic application with no custom icon.
/// </summary>
SIID_APPLICATION = 2,
/// <summary>
/// Folder (generic, unspecified state).
/// </summary>
SIID_FOLDER = 3,
/// <summary>
/// Folder (open).
/// </summary>
SIID_FOLDEROPEN = 4,
/// <summary>
/// 5.25-inch disk drive.
/// </summary>
SIID_DRIVE525 = 5,
/// <summary>
/// 3.5-inch disk drive.
/// </summary>
SIID_DRIVE35 = 6,
/// <summary>
/// Removable drive.
/// </summary>
SIID_DRIVEREMOVE = 7,
/// <summary>
/// Fixed drive (hard disk).
/// </summary>
SIID_DRIVEFIXED = 8,
/// <summary>
/// Network drive (connected).
/// </summary>
SIID_DRIVENET = 9,
/// <summary>
/// Network drive (disconnected).
/// </summary>
SIID_DRIVENETDISABLED = 10,
/// <summary>
/// CD drive.
/// </summary>
SIID_DRIVECD = 11,
/// <summary>
/// RAM disk drive.
/// </summary>
SIID_DRIVERAM = 12,
/// <summary>
/// The entire network.
/// </summary>
SIID_WORLD = 13,
/// <summary>
/// A computer on the network.
/// </summary>
SIID_SERVER = 15,
/// <summary>
/// A local printer or print destination.
/// </summary>
SIID_PRINTER = 16,
/// <summary>
/// The Network virtual folder (FOLDERID_NetworkFolder/CSIDL_NETWORK).
/// </summary>
SIID_MYNETWORK = 17,
/// <summary>
/// The Search feature.
/// </summary>
SIID_FIND = 22,
/// <summary>
/// The Help and Support feature.
/// </summary>
SIID_HELP = 23,
// OVERLAYS...
/// <summary>
/// Overlay for a shared item.
/// </summary>
SIID_SHARE = 28,
/// <summary>
/// Overlay for a shortcut.
/// </summary>
SIID_LINK = 29,
/// <summary>
/// Overlay for items that are expected to be slow to access.
/// </summary>
SIID_SLOWFILE = 30,
// MORE ICONS...
/// <summary>
/// The Recycle Bin (empty).
/// </summary>
SIID_RECYCLER = 31,
/// <summary>
/// The Recycle Bin (not empty).
/// </summary>
SIID_RECYCLERFULL = 32,
/// <summary>
/// Audio CD media.
/// </summary>
SIID_MEDIACDAUDIO = 40,
/// <summary>
/// Security lock.
/// </summary>
SIID_LOCK = 47,
/// <summary>
/// A virtual folder that contains the results of a search.
/// </summary>
SIID_AUTOLIST = 49,
/// <summary>
/// A network printer.
/// </summary>
SIID_PRINTERNET = 50,
/// <summary>
/// A server shared on a network.
/// </summary>
SIID_SERVERSHARE = 51,
/// <summary>
/// A local fax printer.
/// </summary>
SIID_PRINTERFAX = 52,
/// <summary>
/// A network fax printer.
/// </summary>
SIID_PRINTERFAXNET = 53,
/// <summary>
/// A file that receives the output of a Print to file operation.
/// </summary>
SIID_PRINTERFILE = 54,
/// <summary>
/// A category that results from a Stack by command to organize the contents of a folder.
/// </summary>
SIID_STACK = 55,
/// <summary>
/// Super Video CD (SVCD) media.
/// </summary>
SIID_MEDIASVCD = 56,
/// <summary>
/// A folder that contains only subfolders as child items.
/// </summary>
SIID_STUFFEDFOLDER = 57,
/// <summary>
/// Unknown drive type.
/// </summary>
SIID_DRIVEUNKNOWN = 58,
/// <summary>
/// DVD drive.
/// </summary>
SIID_DRIVEDVD = 59,
/// <summary>
/// DVD media.
/// </summary>
SIID_MEDIADVD = 60,
/// <summary>
/// DVD-RAM media.
/// </summary>
SIID_MEDIADVDRAM = 61,
/// <summary>
/// DVD-RW media.
/// </summary>
SIID_MEDIADVDRW = 62,
/// <summary>
/// DVD-R media.
/// </summary>
SIID_MEDIADVDR = 63,
/// <summary>
/// DVD-ROM media.
/// </summary>
SIID_MEDIADVDROM = 64,
/// <summary>
/// CD+ (enhanced audio CD) media.
/// </summary>
SIID_MEDIACDAUDIOPLUS = 65,
/// <summary>
/// CD-RW media.
/// </summary>
SIID_MEDIACDRW = 66,
/// <summary>
/// CD-R media.
/// </summary>
SIID_MEDIACDR = 67,
/// <summary>
/// A writeable CD in the process of being burned.
/// </summary>
SIID_MEDIACDBURN = 68,
/// <summary>
/// Blank writable CD media.
/// </summary>
SIID_MEDIABLANKCD = 69,
/// <summary>
/// CD-ROM media.
/// </summary>
SIID_MEDIACDROM = 70,
/// <summary>
/// An audio file.
/// </summary>
SIID_AUDIOFILES = 71,
/// <summary>
/// An image file.
/// </summary>
SIID_IMAGEFILES = 72,
/// <summary>
/// A video file.
/// </summary>
SIID_VIDEOFILES = 73,
/// <summary>
/// A mixed (media) file.
/// </summary>
SIID_MIXEDFILES = 74,
/// <summary>
/// Folder back. Represents the background Fold of a Folder.
/// </summary>
SIID_FOLDERBACK = 75,
/// <summary>
/// Folder front. Represents the foreground Fold of a Folder.
/// </summary>
SIID_FOLDERFRONT = 76,
/// <summary>
/// Security shield.
/// </summary>
/// <remarks>Use for UAC prompts only. This Icon doesn't work on all purposes.</remarks>
SIID_SHIELD = 77,
/// <summary>
/// Warning (Exclamation mark).
/// </summary>
SIID_WARNING = 78,
/// <summary>
/// Informational (Info).
/// </summary>
SIID_INFO = 79,
/// <summary>
/// Error (X).
/// </summary>
SIID_ERROR = 80,
/// <summary>
/// Key.
/// </summary>
SIID_KEY = 81,
/// <summary>
/// Software.
/// </summary>
SIID_SOFTWARE = 82,
/// <summary>
/// A UI item, such as a button, that issues a rename command.
/// </summary>
SIID_RENAME = 83,
/// <summary>
/// A UI item, such as a button, that issues a delete command.
/// </summary>
SIID_DELETE = 84,
/// <summary>
/// Audio DVD media.
/// </summary>
SIID_MEDIAAUDIODVD = 85,
/// <summary>
/// Movie DVD media.
/// </summary>
SIID_MEDIAMOVIEDVD = 86,
/// <summary>
/// Enhanced CD media.
/// </summary>
SIID_MEDIAENHANCEDCD = 87,
/// <summary>
/// Enhanced DVD media.
/// </summary>
SIID_MEDIAENHANCEDDVD = 88,
/// <summary>
/// Enhanced DVD media.
/// </summary>
SIID_MEDIAHDDVD = 89,
/// <summary>
/// High definition DVD media in the Blu-ray Disc™ format.
/// </summary>
SIID_MEDIABLURAY = 90,
/// <summary>
/// Video CD (VCD) media.
/// </summary>
SIID_MEDIAVCD = 91,
/// <summary>
/// DVD+R media.
/// </summary>
SIID_MEDIADVDPLUSR = 92,
/// <summary>
/// DVD+RW media.
/// </summary>
SIID_MEDIADVDPLUSRW = 93,
/// <summary>
/// A desktop computer.
/// </summary>
SIID_DESKTOPPC = 94,
/// <summary>
/// A mobile computer (laptop).
/// </summary>
SIID_MOBILEPC = 95,
/// <summary>
/// The User Accounts Control Panel item.
/// </summary>
SIID_USERS = 96,
/// <summary>
/// Smart media.
/// </summary>
SIID_MEDIASMARTMEDIA = 97,
/// <summary>
/// CompactFlash media.
/// </summary>
SIID_MEDIACOMPACTFLASH = 98,
/// <summary>
/// A cell phone.
/// </summary>
SIID_DEVICECELLPHONE = 99,
/// <summary>
/// A digital camera.
/// </summary>
SIID_DEVICECAMERA = 100,
/// <summary>
/// A digital video camera.
/// </summary>
SIID_DEVICEVIDEOCAMERA = 101,
/// <summary>
/// An audio player.
/// </summary>
SIID_DEVICEAUDIOPLAYER = 102,
/// <summary>
/// Connect to network.
/// </summary>
SIID_NETWORKCONNECT = 103,
/// <summary>
/// The Network and Internet Control Panel item.
/// </summary>
SIID_INTERNET = 104,
/// <summary>
/// A compressed file with a .zip file name extension.
/// </summary>
SIID_ZIPFILE = 105,
/// <summary>
/// The Additional Options Control Panel item.
/// </summary>
SIID_SETTINGS = 106,
/// <summary>
/// Windows Vista with Service Pack 1 (SP1) and later. High definition DVD drive (any type - HD DVD-ROM, HD DVD-R, HD-DVD-RAM) that uses the HD DVD format.
/// </summary>
SIID_DRIVEHDDVD = 132,
/// <summary>
/// Windows Vista with SP1 and later. High definition DVD drive (any type - BD-ROM, BD-R, BD-RE) that uses the Blu-ray Disc format.
/// </summary>
SIID_DRIVEBD = 133,
/// <summary>
/// Windows Vista with SP1 and later. High definition DVD-ROM media in the HD DVD-ROM format.
/// </summary>
SIID_MEDIAHDDVDROM = 134,
/// <summary>
/// Windows Vista with SP1 and later. High definition DVD-R media in the HD DVD-R format.
/// </summary>
SIID_MEDIAHDDVDR = 135,
/// <summary>
/// Windows Vista with SP1 and later. High definition DVD-RAM media in the HD DVD-RAM format.
/// </summary>
SIID_MEDIAHDDVDRAM = 136,
/// <summary>
/// Windows Vista with SP1 and later. High definition DVD-ROM media in the Blu-ray Disc BD-ROM format.
/// </summary>
SIID_MEDIABDROM = 137,
/// <summary>
/// Windows Vista with SP1 and later. High definition write-once media in the Blu-ray Disc BD-R format.
/// </summary>
SIID_MEDIABDR = 138,
/// <summary>
/// Windows Vista with SP1 and later. High definition read/write media in the Blu-ray Disc BD-RE format.
/// </summary>
SIID_MEDIABDRE = 139,
/// <summary>
/// Windows Vista with SP1 and later. A cluster disk array.
/// </summary>
SIID_CLUSTEREDDRIVE = 140,
/// <summary>
/// The highest valid value in the enumeration. Values over 160 are Windows 7-only icons.
/// </summary>
SIID_MAX_ICONS = 175
}
public class IconUtils
{
// copy DLL declarations above here...
// ...
// and copy again the XML summary here.
public static bool DestroyIconH(IntPtr iconHandle)
{
return DestroyIcon(iconHandle);
}
/// <summary>
/// Gets the Pointer to the (stock) Icon associated to the specified ID.
/// </summary>
/// <param name="StockIconID">Icon ID among the defined Stock ones.</param>
/// <returns>The Pointer to the retrieved Icon. If no Icon were found, an empty Pointer is returned.</returns>
private static IntPtr GetShellIconPointer(SHSTOCKICONID StockIconID, SHGSI IconOptions)
{
SHSTOCKICONINFO StkIconInfo = new SHSTOCKICONINFO();
StkIconInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(typeof(SHSTOCKICONINFO)));
if (SHGetStockIconInfo(StockIconID, IconOptions, StkIconInfo) == 0) {
return StkIconInfo.hIcon;
}
return IntPtr.Zero;
}
/// <summary>
/// Gets the (stock) Icon associated to the specified ID.
/// </summary>
/// <param name="StockIconID">Icon ID among the defined Stock ones.</param>
/// <returns>The (stock) Icon. If no Icon were found, Null is returned.</returns>
/// <remarks>WARNING ! Caller is responsible of calling Dispose() on the returned Icon.</remarks>
public static Icon GetSystemIcon(SHSTOCKICONID stockIconID, SHGSI iconOptions)
{
IntPtr iconPointer = GetShellIconPointer(stockIconID, iconOptions);
if (iconPointer != IntPtr.Zero) {
Icon actualIcon = Icon.FromHandle(iconPointer);
Icon iconCopy = (System.Drawing.Icon)actualIcon.Clone();
actualIcon.Dispose();
DestroyIcon(iconPointer);
/*
Honestly, I'm unsure of what I'm doing here :-(
If I get rid of either actualIcon or iconCopy,
and don't make a copy of it, I get a 0x0 Icon.
If I don't call DestroyIcon(h), I get a memory leak.
I highly doubt a memory leak won't occur even with the trick above,
but heh! >:-D honestly I don't care since
everything related to Icon retrieval in Windows
appears to me a very bad design pattern in the first place.
*/
return iconCopy;
} else {
return null;
}
}
}
System.Drawing.Bitmap创建扩展方法。默认的CreateThumbnail()不适合我的需求:/// <summary>
/// Creates a Thumbnail of the Bitmap.
/// </summary>
/// <param name="sourceBitmap">Source Bitmap.</param>
/// <param name="width">Width for the Tumbnail.</param>
/// <param name="height">Height for the Tumbnail.</param>
/// <returns>Returns the created Thumbnail.</returns>
[Extension()]
public Bitmap CreateThumbnail(this Bitmap sourceBitmap, Int32 width, Int32 height)
{
if (sourceBitmap == null) {
return null; // Eat Exception !
} else {
if ((width > 0) && (height > 0)) {
Rectangle layoutRectangle = new Rectangle(0, 0, width, height);
Bitmap thumbnailBitmap = new Bitmap(width, height, sourceBitmap.PixelFormat);
using (Graphics bmpGrphics = thumbnailBitmap.CreateGraphics()) {
bmpGrphics.DrawImage(sourceBitmap, layoutRectangle);
}
return thumbnailBitmap;
} else {
return null;
}
}
}
SHSTOCKICONID值之一)// You're looking for a 16x16 opened folder icon :
Icon icon16 = IconUtils.GetShellIcon(SHSTOCKICONID.SIID_FOLDEROPEN, SHGSI.SHGSI_ICON Or SHGSI.SHGSI_SMALLICON);
// You're looking for a 32x32 default state folder icon :
Icon icon32 = IconUtils.GetShellIcon(SHSTOCKICONID.SIID_FOLDER, SHGSI.SHGSI_ICON Or SHGSI.SHGSI_LARGEICON);
SHGSI.SHGSI_SMALLICON Or SHGSI.SHGSI_LARGEICON,但这不起作用(至少在我的系统上)。似乎未通过SHGSI_ICON标志将阻止在结构中正确设置图标句柄。而且我完全没有图标。SHSTOCKICONID.SIID_FOLDER和SHSTOCKICONID.SIID_FOLDEROPEN由完全相同的图标表示。 MS失败恕我直言!有时,我只是使用SHSTOCKICONID.SIID_FOLDERBACK来显示已关闭状态,但是您可以自由选择适合您(和用户)需求的状态。imgList16和imgList32-或类似)。通常,您将始终拥有16x16和32x32版本,并以适合您的显示器的格式返回(如MS广告所示)。但是我不指望,我总是检查一下我是否都:// Get the two icons...
Icon dirIcon16 = Icon_Class.GetShellIcon(SHSTOCKICONID.SIID_FOLDEROPEN, SHGSI.SHGSI_ICON | SHGSI.SHGSI_SMALLICON);
Icon dirIcon32 = Icon_Class.GetShellIcon(SHSTOCKICONID.SIID_FOLDEROPEN, SHGSI.SHGSI_ICON | SHGSI.SHGSI_LARGEICON);
// Make sure you have both...
if (DirIcon16 == null) {
if (DirIcon32 == null) {
// both are missing... use a placeholder bitmap instead.
// do the necessary changes and checks...
} else {
// at least the 32x32 is available.
Bitmap iconBitmap32 = dirIcon32.ToBitmap();
Bitmap iconBitmap16 = iconBitmap32.CreateThumbnail(16, 16);
// now you can add both in two ImageList...
imgList16.Images.Add("Directory_Opened", iconBitmap16);
imgList32.Images.Add("Directory_Opened", iconBitmap32);
dirIcon32.Dispose();
}
} else {
Bitmap iconBitmap16 = dirIcon16.ToBitmap();
imgList16.Images.Add("Directory_Opened", iconBitmap16);
if (dirIcon32 == null) {
Bitmap iconBitmap32 = iconBitmap16.CreateThumbnail(32, 32);
imgList32.Images.Add("Directory_Opened", iconBitmap32);
} else {
Bitmap iconBitmap32 = dirIcon32.ToBitmap();
imgList32.Images.Add("Directory_Opened", iconBitmap32);
dirIcon32.Dispose();
}
dirIcon16.Dispose();
}
// hence the extension above.
SHGSI枚举来检索这些信息。关于c# - 您可以从系统中获取默认文件夹的打开/关闭图标而没有实际路径吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32914212/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html