简体   繁体   中英

C#: Renaming a file in a DragAndDrop listbox control

First I really wanted to solve this myself but I've I haven't written to textfiles for a while. I'm trying to rename a file really any file, after I put it into the drag & drop box but then C# says it can't find the specified file.

I'm uploading my project to Dropbox so anyone who wants to help doesn't need to replicate it from scratch: https://www.dropbox.com/s/9cta5dsrzosk81t/DragDropForm.v12.suo?dl=0

But here's my code anyway if it's easier for people to answer my question with. Thank you.

    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;
        }
    }

I think the problem is in this line:

FileInfo fi = new FileInfo(filename);

You've got to pass file (the full path) to FileInfo like this:

FileInfo fi = new FileInfo(file);

The same would apply to getDirectoryName(filename) , should be getDirectoryName(file); , although you are not using that method returning value for anything...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM