Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello =)

regrettably I have no idea about C#. It's my first little C# project.

I just want to move all Excel files from the folder A to B. That's it.

Unfortunately, the files are not moved. =( I hope you can help me.

What I have tried:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Move
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                
                string sourceFile = @"C:\Users\Chris\Desktop\*.xlsx";
                string destinationFile = @"C:\Users\Chris\Documents\Excel\*.xlsx";
                File.Move(sourceFile, destinationFile);
                Directory.Move(@"C:\Users\Chris\Desktop\", @"C:\Users\Chris\Documents\Excel");

            }
            finally
            {
                Console.WriteLine("yay");
            }
        }
    }
}
Posted
Updated 20-Dec-18 2:40am

1 solution

File.Move will only move a single file; it doesn't know how to process wildcards.

You need to list the files you want to move, and move them individually:
C#
string sourcePath = @"C:\Users\Chris\Desktop\";
string destinationPath = @"C:\Users\Chris\Documents\Excel\";
foreach (string sourceFile in Directory.GetFiles(sourcePath, "*.xlsx"))
{
    string fileName = Path.GetFileName(sourceFile);
    string destinationFile = Path.Combine(destinationPath, fileName);
    File.Move(sourceFile, destinationFile);
}


File.Move(String, String) Method (System.IO) | Microsoft Docs[^]
Directory.GetFiles Method (System.IO) | Microsoft Docs[^]
Path.GetFileName Method (System.IO) | Microsoft Docs[^]
Path.Combine Method (System.IO) | Microsoft Docs[^]
 
Share this answer
 
v2
Comments
uncommon_name 20-Dec-18 9:07am    
How can I override the files in the destination folder?
Richard Deeming 20-Dec-18 9:14am    
Unfortunately, File.Move doesn't provide an "overwrite" option. You'll need to test whether the destination file exists, and delete it:
if (File.Exists(destinationFile)) File.Delete(destinationFile);
File.Move(sourceFile, destinationFile);
MadMyche 20-Dec-18 9:17am    
2 options- you can use an if File.Exists { File.Delete();} routine or you can place the File.Move() in a Try...Catch block and place the Delete within the Catch statement if it is a file already exists error

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900