C#:重命名 DragAndDrop 列表框控件中的文件

C#: Renaming a file in a DragAndDrop listbox control

首先,我真的很想自己解决这个问题,但我已经有一段时间没有写入文本文件了。在我将文件放入拖放框之后,我试图重命名一个文件,实际上是任何文件,但 C# 说它找不到指定的文件。

我正在将我的项目上传到 Dropbox,这样任何想要提供帮助的人都不需要从头开始复制它: https://www.dropbox.com/s/9cta5dsrzosk81t/DragDropForm.v12.suo?dl=0

但是如果人们更容易回答我的问题的话,这里还是我的代码。谢谢。

    public Form1()
    {
        InitializeComponent();
    }


    private string getFileName(string path)
    {            
        return Path.GetFileName(path);
    }

    private string getDirectoryName(string path)
    {
        return Path.GetDirectoryName(path);
    }


    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        //TAKE dropped items and store in array.
        string[] dropppedFiles = (string[])e.Data.GetData(DataFormats.FileDrop);

        //LOOP through all droppped items and display them
        foreach (string file in dropppedFiles)
        {
            string filename = getFileName(file);         
            listBox1.Items.Add(filename);
            FileInfo fi = new FileInfo(filename);
            {
                //IF filename "NewName" doesn't exist in drag drop box.
                if (!File.Exists("NewName"))
                {                        
                    getDirectoryName(filename);
                    fi.MoveTo("NewName");
                }
            }
        }
    }

    private void Form1_DragEnter(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
        {
            e.Effect = DragDropEffects.All;
        }
    }

我认为问题出在这一行:

FileInfo fi = new FileInfo(filename);

您必须像这样将 file(完整路径)传递给 FileInfo

FileInfo fi = new FileInfo(file);

这同样适用于 getDirectoryName(filename),应该是 getDirectoryName(file);,尽管您没有使用该方法返回任何值...