move a file in csharp

To move a file from one location to another in C#, you can use the File.Move method provided in the System.IO namespace. This method renames a specified file and moves it to a new location, if the new location is on the same volume. If the new location is on a different volume, you can use the File.Copy method to copy the file to the new location, and then delete the original file.

Here's an example code snippet that demonstrates moving a file from one location to another:

main.cs
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string sourceFile = @"C:\Projects\FileHandling\SampleFile.txt";
        string destinationFile = @"C:\Projects\FileHandling\NewFolder\SampleFile.txt";

        try
        {
            // Ensure that the target directory exists
            string destinationDirectory = Path.GetDirectoryName(destinationFile);
            if (!Directory.Exists(destinationDirectory))
            {
                Directory.CreateDirectory(destinationDirectory);
            }

            // Move the file to the new location
            File.Move(sourceFile, destinationFile);
            Console.WriteLine("File moved successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred while moving the file: " + ex.Message);
        }
    }
}
876 chars
30 lines

In this example, we first specify the source file path and the destination file path. We then check if the target directory exists, and create it if it doesn't. Finally, we call the File.Move method to move the file to the new location. If any errors occur during the file move operation, we catch them and display an error message.

gistlibby LogSnag