使用.NET从设备拖动文件并复制到本地硬盘驱动器

时间:2012-06-12 07:01:53

标签: .net drag-and-drop filestream

我正在使用此代码将拖动的文件捕获到我的表单中并将其复制到特定文件夹(我已将复制过程保留,但我正在使用 - FileSystem.CopyDirectory(copyFileDetails.Dir.FullName, copyFileDetails.Target, UIOption.AllDialogs); and FileSystem.CopyFile(file, newFileName, UIOption.AllDialogs);

this.DragEnter += new DragEventHandler(Form1_DragEnter);
this.DragDrop += new DragEventHandler(Form1_DragDrop);

private void Form1_DragEnter(object sender, DragEventArgs e)
{
    //string action = e.Data.ToString();
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
        e.Effect = DragDropEffects.Copy;
    else if (e.Data.GetDataPresent("FileGroupDescriptorW"))
    {
        System.IO.MemoryStream info = e.Data.GetData("FileGroupDescriptor") as System.IO.MemoryStream;
        System.IO.MemoryStream content = e.Data.GetData("FileGroupDescriptorW") as System.IO.MemoryStream;
        e.Effect = DragDropEffects.Copy;

    }
}

private void Form1_DragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
    }
    else if (e.Data.GetDataPresent("FileGroupDescriptorW"))
    {
        System.IO.MemoryStream info = e.Data.GetData("FileGroupDescriptor") as System.IO.MemoryStream;
        System.IO.MemoryStream content = e.Data.GetData("FileGroupDescriptorW") as System.IO.MemoryStream;
        ClipboardMemoryStream = (MemoryStream)e.Data.GetData("FileGroupDescriptorW", true);
        byteArray = ClipboardMemoryStream.ToArray();

        // TODO: Read data from stream
    }
}

现在,当我将文件拖到表单中时,我正在获取文件名(string []文件),并且没有问题将其复制到硬盘驱动器中。

但是当从设备(比如相机)拖动文件时,我得到一个文件流,我不知道如何变成一个与原始文件同名的文件。 我还需要它来支持大文件和文件夹。

我该如何实现?

1 个答案:

答案 0 :(得分:0)

尝试以下代码从filegroupdescriptor中读取文件名:

Dim ioStream As System.IO.Stream = DirectCast(e.Data.GetData("FileGroupDescriptor"), System.IO.Stream)
Dim contents As Byte() = New [Byte](511) {}
ioStream.Read(contents, 0, 512)
ioStream.Close()
Dim sb As New System.Text.StringBuilder()
Dim i As Integer = 76
While contents(i) <> 0
    sb.Append(CChar(ChrW(contents(i))))
    i += 1
End While

filename = sb.ToString()