How to move a file in C#
By FoxLearn 6/11/2024 2:18:38 AM 89
In C#, you can move a file from one location to another using the System.IO namespace, which provides classes for working with files and directories.
Specifically, you can use the File.Move method to move a file. Here is an example to demonstrate how to move a file in c#.
using System; using System.IO; class Program { static void Main() { string sourceFilePath = @"c:\source\file.txt"; string destinationFilePath = @"c:\destination\file.txt"; try { // Ensure that the target does not exist if (File.Exists(destinationFilePath)) { Console.WriteLine("Destination file already exists. Choose a different path or delete the existing file."); return; } // c# move the file File.Move(sourceFilePath, destinationFilePath); } catch (Exception ex) { Console.WriteLine("An unexpected error occurred: " + ex.Message); } } }
You can also use the FileInfo
class to move the file.
string fileName = @"C/:fileName.txt"; FileInfo fi = new FileInfo(fileName); string destinationFile = @"C:/destinationFile.txt"; try { fi.MoveTo(destinationFile); } catch (IOException ex) { Console.WriteLine(ex.Message); }
The MoveTo
method in C# relocates an existing file to a new location, which can have the same or a different file name. It requires the full path of both the source and destination files. Once the move is completed, the original file is deleted from its initial location.
Categories
Popular Posts
How to Download Chromedriver for Selenium
08/29/2024
C# Tutorial
07/20/2024
How to Download Microsoft SQL Server
06/22/2024