c# - 删除的 zip 文件会导致 e.Data.GetData ("FileContents") 引发异常

标签 c# .net wpf drag-and-drop zip

我正在尝试在 WPF 应用程序中为从 zip 存档中拖动的文件实现一个处理程序。处理程序应获取文件内容以进行进一步处理。

我的环境:Windows7、安装了 7-zip、Visual Studio 2012 Express、.Net 4.5

下面是一个简单的 MainWindow 应用程序的代码,用于演示该问题:

public partial class MainWindow : Window
{
  public MainWindow()
  {
    InitializeComponent();
    AllowDrop= true;
    Drop += onDrop;
  }

  private void onDrop(object sender, DragEventArgs e)
  {
    if (e.Data.GetDataPresent("FileContents"))
    {
      var fileContents = e.Data.GetData("FileContents");
      //get file contents...
    }
  }
}

当我将 zip 存档中包含的文件拖到窗口中时,对 e.Data.GetData("FileContents") 的调用会抛出 System.ArgumentException(“参数超出范围”),调用堆栈如下:

System.Windows.DataObject.OleConverter.GetDataInner(formatetc, medium)  
System.Windows.DataObject.OleConverter.GetDataFromOleHGLOBAL(format, aspect, index) 
System.Windows.DataObject.OleConverter.GetDataFromBoundOleDataObject(format, aspect, index) 
System.Windows.DataObject.OleConverter.GetData(format, autoConvert, aspect, index)  
System.Windows.DataObject.OleConverter.GetData(format, autoConvert) 
System.Windows.DataObject.GetData(format, autoConvert)  
System.Windows.DataObject.GetData(format)   
TestZip.MainWindow.onDrop(sender, e) Zeile 34   C#

我查找了此 OleConverter ( http://reflector.webtropy.com/default.aspx/Dotnetfx_Win7_3@5@1/Dotnetfx_Win7_3@5@1/3@5@1/DEVDIV/depot/DevDiv/releases/Orcas/NetFXw7/wpf/src/Core/CSharp/System/Windows/dataobject@cs/1/dataobject@cs ) 的源代码,但 GetDataInner() 方法的实现如下

private void GetDataInner(ref FORMATETC formatetc, out STGMEDIUM medium)
 { 
     new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); // BlessedAssert
     try
     { 
             _innerData.GetData(ref formatetc, out medium);
     } 
     finally
     {
         SecurityPermission.RevertAssert();
     } 
 }

因此,这也没有提供有关此处问题的更多信息。

我还尝试使用已卸载的 7-zip 和不同的 zip 存档,但没有任何变化。

我的问题:有人知道这里出了什么问题吗?我需要做什么才能从 zip 存档中获取文件的内容放到我的窗口上?

最佳答案

老问题,但我今天需要这样做......

使用语句:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;

引用演示核心 https://msdn.microsoft.com/en-us/library/system.windows.idataobject(v=vs.110).aspx

首先,您需要获取“FileDescriptor”内容,这是一个读取它们的类。

/// <summary>
/// Specifies which fields are valid in a FileDescriptor Structure
/// </summary>    
[Flags]
enum FileDescriptorFlags : uint
{
    ClsId = 0x00000001,
    SizePoint = 0x00000002,
    Attributes = 0x00000004,
    CreateTime = 0x00000008,
    AccessTime = 0x00000010,
    WritesTime = 0x00000020,
    FileSize = 0x00000040,
    ProgressUI = 0x00004000,
    LinkUI = 0x00008000,
    Unicode = 0x80000000,
}

internal static class FileDescriptorReader
{        
    internal sealed class FileDescriptor
    {
        public FileDescriptorFlags Flags{get;set;}
        public Guid ClassId{get;set;}
        public Size Size{get;set;}
        public Point Point{get;set;}
        public FileAttributes FileAttributes{get;set;}
        public DateTime CreationTime{get;set;}
        public DateTime LastAccessTime{get;set;}
        public DateTime LastWriteTime{get;set;}
        public Int64 FileSize{get;set;}
        public string FileName{get;set;}

        public FileDescriptor(BinaryReader reader)
        {
            //Flags
            Flags = (FileDescriptorFlags)reader.ReadUInt32();
            //ClassID
            ClassId = new Guid(reader.ReadBytes(16));
            //Size
            Size = new Size(reader.ReadInt32(), reader.ReadInt32());
            //Point
            Point = new Point(reader.ReadInt32(), reader.ReadInt32());
            //FileAttributes
            FileAttributes = (FileAttributes)reader.ReadUInt32();
            //CreationTime
            CreationTime = new DateTime(1601,1,1).AddTicks(reader.ReadInt64());
            //LastAccessTime
            LastAccessTime = new DateTime(1601,1,1).AddTicks(reader.ReadInt64());
            //LastWriteTime
            LastWriteTime = new DateTime(1601, 1, 1).AddTicks(reader.ReadInt64());
            //FileSize
            FileSize = reader.ReadInt64();
            //FileName
            byte[] nameBytes = reader.ReadBytes(520);
            int i = 0; 
            while(i < nameBytes.Length)
            {
                if (nameBytes[i] == 0 && nameBytes[i + 1] == 0)
                    break;
                i++;
                i++;
            }
            FileName = UnicodeEncoding.Unicode.GetString(nameBytes, 0, i);
        }
    }

    public static IEnumerable<FileDescriptor> Read(Stream fileDescriptorStream)
    {
        BinaryReader reader = new BinaryReader(fileDescriptorStream);
        var count = reader.ReadUInt32();
        while (count > 0)
        {
            FileDescriptor descriptor = new FileDescriptor(reader);

            yield return descriptor;

            count--;
        }
    }

    public static IEnumerable<string> ReadFileNames(Stream fileDescriptorStream)
    {
        BinaryReader reader = new BinaryReader(fileDescriptorStream);
        var count = reader.ReadUInt32();
        while(count > 0)
        {
            FileDescriptor descriptor = new FileDescriptor(reader);

            yield return descriptor.FileName;

            count--;
        }
    }
}

现在使用它您可以获得每个文件的匹配文件内容:

static class ClipboardHelper
{
    internal static MemoryStream GetFileContents(System.Windows.IDataObject dataObject, int index)
    {
        //cast the default IDataObject to a com IDataObject
        IDataObject comDataObject;
        comDataObject = (IDataObject)dataObject;

        System.Windows.DataFormat Format = System.Windows.DataFormats.GetDataFormat("FileContents");
        if (Format == null)
            return null;

        FORMATETC formatetc = new FORMATETC();
        formatetc.cfFormat = (short)Format.Id;
        formatetc.dwAspect = DVASPECT.DVASPECT_CONTENT;
        formatetc.lindex = index;
        formatetc.tymed = TYMED.TYMED_ISTREAM | TYMED.TYMED_HGLOBAL;


        //create STGMEDIUM to output request results into
        STGMEDIUM medium = new STGMEDIUM();

        //using the com IDataObject interface get the data using the defined FORMATETC
        comDataObject.GetData(ref formatetc, out medium);

        switch (medium.tymed)
        {
            case TYMED.TYMED_ISTREAM: return GetIStream(medium);
            default: throw new NotSupportedException();
        }
    }

    private static MemoryStream GetIStream(STGMEDIUM medium)
    {
        //marshal the returned pointer to a IStream object
        IStream iStream = (IStream)Marshal.GetObjectForIUnknown(medium.unionmember);
        Marshal.Release(medium.unionmember);

        //get the STATSTG of the IStream to determine how many bytes are in it
        var iStreamStat = new System.Runtime.InteropServices.ComTypes.STATSTG();
        iStream.Stat(out iStreamStat, 0);
        int iStreamSize = (int)iStreamStat.cbSize;

        //read the data from the IStream into a managed byte array
        byte[] iStreamContent = new byte[iStreamSize];
        iStream.Read(iStreamContent, iStreamContent.Length, IntPtr.Zero);

        //wrapped the managed byte array into a memory stream
        return new MemoryStream(iStreamContent);
    }
}

现在您可以枚举文件内容中的流:

                var fileDescriptor = (MemoryStream)Clipboard.GetDataObject().GetData("FileGroupDescriptorW");
                var files = FileDescriptorReader.Read(fileDescriptor);
                var fileIndex = 0;
                    foreach (var fileContentFile in files)
                    {
                        if ((fileContentFile.FileAttributes & FileAttributes.Directory) != 0)
                        {
                            //Do something with directories?
                            //Note that directories do not have FileContents
                            //And will throw if we try to read them
                        }
                        else
                        {
                            var fileData = ClipboardHelper.GetFileContents(Clipboard.GetDataObject(), FileIndex);
                            fileData.Position = 0;
                            //Do something with the fileContent Stream
                        }
                        fileIndex++;                            
                    }

关于c# - 删除的 zip 文件会导致 e.Data.GetData ("FileContents") 引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24985239/

相关文章:

c# - 在 MVC.Net 中链接 lambda 表达式,而无需重复传递 HtmlHelper 对象

c# - LINQ .ToList() 在单个结果上失败

c# - 从以 Task 为返回类型的非异步方法返回什么?

c# - 枚举类模式是否与 DI 不兼容?

WPF/Silverlight状态-是否从XAML激活?

c# - 更好的数据表

c# - 菜鸟事: How to collect data from multiple tables most deftly?

c# - 如何使只读结构 XML 可序列化?

C# WPF 上下文菜单项单击事件返回 null

WPF:如何制作颜色变化的动画?