用户右键单击文件(例如在桌面上)并单击“复制”.现在如何在C#中确定复制到剪贴板的文件是否为图像类型?
Clipboard.ContainsImage()在这种情况下不起作用
以下确定是否将图像直接复制到剪贴板,而不是将文件复制到剪贴板
IDataObject d = Clipboard.GetDataObject(); if(d.GetDataPresent(DataFormats.Bitmap)) { MessageBox.Show("image file found"); }
为了清楚起见,我想确定复制到剪贴板的’文件’是否是图像.
编辑:答案很棒,但如何将文件的文件名复制到剪贴板? Clipboard.getText()似乎不起作用.. Edit2:Clipboard.GetFileDropList()的工作原理
解决方法
你可以像这样检查它(没有内置的方法这样做)
读取文件并在图形图像对象中使用它,如果它将是图像,它将工作正常,否则它将引发OutOfMemoryException.
读取文件并在图形图像对象中使用它,如果它将是图像,它将工作正常,否则它将引发OutOfMemoryException.
这是一个示例代码:
bool IsAnImage(string filename) { try { Image newImage = Image.FromFile(filename); } catch (OutOfMemoryException ex) { // Image.FromFile will throw this if file is invalid. return false; } return true; }
它适用于BMP,GIF,JPEG,PNG,TIFF文件格式
更新
IDataObject d = Clipboard.GetDataObject(); if(d.GetDataPresent(DataFormats.FileDrop)) { //This line gets all the file paths that were selected in explorer string[] files = d.GetData(DataFormats.FileDrop); //Get the name of the file. This line only gets the first file name if many file were selected in explorer string TheImageFile = files[0]; //Use above method to check if file is Image file if(IsAnImage(TheImageFile)) { //Process file if is an image } { //Process file if not an image } }