SoFunction
Updated on 2025-03-06

Summary of 9 ways to copy files in C#

introduction

Recently, I encountered a problem. One program called another program's file, but the other program's file was occupied and the file could not be used. The solution at this time is to copy the file of another program to the current program. This article introduces three ways to copy files using C#.

1、Copy

This is a commonly used method for copying files in C#. It is a method below File. This method is suitable for copying files without special requirements. The usage method is as follows:

stringsourceFile=@"c:\temp\";
stringtagretFile=@"c:\temp\";
if(!(@"c:\temp"))
 //You need to determine whether the folder exists  (path);//If it is equal to true, overwrite the target directory file, otherwise do not overwrite bool isrewrite=true;(sourcePath, targetPath, isrewrite);

2、CopyTo

If you have more advanced needs, you can consider copying files using CopyTo. The CopyTo method can return a FileInfo type, representing the new file information after the copy operation; and CopyTo supports copying files in different file systems; the CopyTo method can use the FileOptions enumeration to specify operation behavior, such as specifying whether to overwrite the target file, whether to allow cache to be bypassed during copying, etc.

 
string sourceFile = @"c:\temp\"; 
string tagretFile = @"c:\temp\"; 
FileInfo file = new FileInfo(sourceFile); 
if () //You can determine whether the source file exists{ 
    // If true here is overridden    (tagretFile , true); 
}

3. Use file stream reading and writing to implement Copy

If you have higher needs, you can use file streaming to copy, the code is as follows:

 
uing ;
public static void CopyFileUsingFileStream(string sourceFilePath, string destFilePath)
{
    // Create a file stream and read the file    using (FileStream sourceStream = new FileStream(sourceFilePath, ))
    {
        // Create a new file stream and write it        using (FileStream destStream = new FileStream(destFilePath, ))
        {
            // Create a buffer to store the read data            byte[] buffer = new byte[1024];
            // Read data and write to the target file stream            int bytesRead;
            while ((bytesRead = (buffer, 0, )) > 0)
            {
                (buffer, 0, bytesRead);
            }
        }
    }
}
//Calling method    #region
    string sourceFile = @"e:\temp\";
    string tagretFile = @"e:\temp\";
    CopyFileUsingFileStream(sourceFile, tagretFile);
    #endregion

There are several benefits of copying files using file streams:

Higher flexibility:Using file streams allows you to control the way data is read and written more flexibly, such as customizing the buffer size, setting the starting position of read and write, and so on. These flexibility can meet more needs than just simple file copies.

Higher performance:Using file streams allows for higher performance because it reduces the number of disk I/O operations by cached data, thereby increasing the efficiency of reading and writing data. Furthermore, using buffers of appropriate sizes can further improve performance.

Better resource management:Use the FileStream class to better manage resources because it implements the IDisposable interface, which can release resources in time after using the file stream. This can avoid resource leakage and system performance degradation.

Better error handling:Using file streams can better handle errors, such as the possible exceptions when reading or writing data, when you can use the try-catch statement to catch and handle the error. This can improve the robustness and reliability of the code.

4. How to use:

This is the most direct way to copy the source file to the destination location.

using ;

 

// ...

 

string sourceFile = @"C:\path\to\source\";

string destinationFile = @"C:\path\to\destination\";

(sourceFile, destinationFile);

5. The overloaded version of the method contains whether to overwrite the boolean value:

If you want to control whether to overwrite files that already exist at the target location, you can use this overloaded version.

(sourceFile, destinationFile, true); // If the target file already exists,Cover it

6. Use FileInfo class:

The FileInfo class provides operations on files, including copying.

FileInfo fileInfo = new FileInfo(sourceFile);

(destinationFile, true); // The second parameter determines whether to overwrite the target file

7. Use Stream to copy:

Copying of files can be achieved by reading the content stream of the source file and writing it to the target file stream. This approach may be more efficient when dealing with large files, as it allows you to process file content in chunks and avoid loading the entire file into memory at once.

using (FileStream sourceStream = (sourceFile))

using (FileStream destinationStream = (destinationFile))

{
    (sourceStream); // WriteFrom is a custom extension method, you need to implement it yourself
}

Note: The WriteFrom above is a hypothetical extension method, which needs to be implemented by itself when actually using it. It can read the content of the sourceStream by looping and write it to the destinationStream.

8. Use and class to copy files:

Although these two classes are mainly used to process paths and directories, they can be copied in combination with methods.

string sourceDirectory = (sourceFile);

string destinationDirectory = @"C:\path\to\destination";

string destinationFileName = (sourceFile);

string fullDestinationPath = (destinationDirectory, destinationFileName);

 

(sourceFile, fullDestinationPath);

9. Use asynchronous method to copy the file:

If you are writing an application that needs to handle a lot of files or needs to keep UI responsive, consider using an asynchronous approach.

await (sourceFile, destinationFile, true); // Copy files asynchronously

Each method has its applicable scenarios, and you need to choose the most suitable method according to your specific needs. For example, if you need more fine-grained control (such as handling errors during replication), you may need to use Stream. If it's just a simple file copy operation, the method may be sufficient.

Conclusion

This article introduces many ways to copy files in C#, mainly introduces the methods of Copy, CopyTo and file streaming, and lists some of their respective features and advantages for your reference when using it. No matter which method is used, security and robustness should be taken into account. When copying files, it is necessary to ensure that both the source and target files exist and have appropriate permissions, and to consider possible errors and exceptions and perform appropriate error handling.

The above is the detailed content of the 9 methods to copy files in C#. For more information about copying files in C#, please pay attention to my other related articles!