Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file.Move without renaming it

Im coding a programm, which should read out the id3 tags of mp3 files, create a Directory named like the artist and then i want to move the mp3 files into the specific artist directory.

When im trying to Move the Mp3 file, it doesnt move it into the subfolder(named like the Artist) of my Musik Directory, which i created. I just want to Move the Mp3 files, not rename them.

here is my code:

   public void moveFiles(string path, string[] title, string[] artist,string [] songs)
    {//loop through the title array
        for(int i=0;i<title.Length;i++)
        {// no artist no name
            if (artist[i] == null)
            { 
                i += 1;
            }//check if sourceFile is existing
            if (File.Exists(songs[i]))
            {//check if destinationFile is existing
                if (File.Exists((@"C:\Musik\" + artist[i] + songs[i])))
                {//if delete
                    File.Delete((@"C:\Musik\" + artist[i] + songs[i]));
                } 
                else
                { //move file from songs[i](sourcePath)to (destinationPath)
                    File.Move(songs[i],(@"C:\Musik\" + artist[i] + songs[i]));                  
                    MessageBox.Show("Das Lied " + title[i] + " wurde erfolgreich verschoben");
                }
            }
            else
            {
                MessageBox.Show(songs[i]+" does not exist!");
            }
        }
    }

It only moves my files into the C:\Musik Directory and it's renaming my files like Artist-Song; Any help is welcome. Thanks:)

like image 894
Hansanho Avatar asked Dec 26 '22 09:12

Hansanho


2 Answers

You have missed a backslash in your path. I would strongly suggest using Path.Combine for this type of thing too. It makes it far more readable and is a cleaner way than pure string concatenation. Also Path.GetFileName() is super useful... know it / love it ;)

File.Move(songs[i], Path.Combine(@"C:\Musik", Path.Combine(artist[i], Path.GetFileName(songs[i]));

UPDATE

If you are targeting .Net 4.0 or higher you can use the 4 string override to make this cleaner (as is pointed out in the suggestions). If you are targeting 3.5 or lower, use the top solution.

File.Move(songs[i], Path.Combine(@"C:", "Musik", artist[i], Path.GetFileName(songs[i]));
like image 166
Evan L Avatar answered Jan 07 '23 07:01

Evan L


You have missed one backslash ("\") in your code.

// By popular suggestion, using Path.Combine...
const string dstRootDirectoryName = @"C:\Musik";
var destinationFileName = Path.Combine(dstRootDirectoryName, artist[i], songs[i]);
if (File.Exists(destinationFileName)
{
    File.Delete(destinationFileName);
}
else
{
    File.Move(songs[i], destinationFileName);
    MessageBox.Show("The file:" + title[i] + " was moved");
}
like image 20
HuorSwords Avatar answered Jan 07 '23 06:01

HuorSwords