📅  最后修改于: 2023-12-03 14:59:40.760000             🧑  作者: Mango
As a programmer, file management is a crucial aspect of your work. In C#, renaming a file is a common requirement. Additionally, adding a file to a directory is also a frequent task. In this article, we will learn how to rename a file and add a file using C#.
To rename a file in C#, we need to use the System.IO.File
class. The File
class provides various static methods to manipulate files. To rename a file, we can call the File.Move()
method and pass the old file path and the new file path as arguments.
string oldFilePath = @"C:\oldFile.txt";
string newFilePath = @"C:\newFile.txt";
File.Move(oldFilePath, newFilePath);
The above code will rename the oldFile.txt
file to newFile.txt
.
To add a file to a directory, we can use the File.Copy()
method provided by the System.IO.File
class. This method creates a copy of the file at the specified path.
string sourceFilePath = @"C:\sourceFile.txt";
string destinationDirectoryPath = @"C:\DestinationFolder";
string destinationFilePath = Path.Combine(destinationDirectoryPath, Path.GetFileName(sourceFilePath));
File.Copy(sourceFilePath, destinationFilePath);
The above code will copy the sourceFile.txt
file to the DestinationFolder
. The Path.Combine()
method is used to combine the destination directory path with the file name.
In this article, we have learned how to rename a file and add a file to a directory using C#. With the help of the System.IO.File
class, we can easily manipulate files and directories in C#.