The best VPN 2024

The Best VPS 2024

The Best C# Book

how to use 1 line C# code implement copy folder?

Spread the love

How to use 1 line of C# code implement copy folder? As a C# developer, when encountering functions such as uploading files, I often have the function of copying folders in C#, and usually use the class library of the System.IO namespace to perform file operations. Not long ago, I was writing a batch clone. When I used the function of the git repository, I also encountered a similar function. Let me tell you what I used to achieve the function of copying a folder with only one line of code.

Before starting the topic, let’s review some common writing methods. By the way, using the methods provided in this article, you can also achieve C# copy folder, C# rename folder, C# rename file, C# move file, and C# move The function of the directory is only one line of code.

how to use 1 line C# code implement copy folder?
how to use 1 line C# code implement copy folder?

C# code implement copy folder

The following is our common code to copy the contents of a folder to a new directory by looping, maybe many people will write this way.

        /// <summary>
        /// Copy a directory (posted on https://znlive.com first) to a new directory, if the target directory does not exist, create a new one
        /// </summary>
        /// <param name="sourceDir">Source Directory</param>
        /// <param name="destDir">Destination directory</param>
        private static void CopyFolder(string sourceDir, string destDir)
        {
            if (!Directory.Exists(destDir))
            {
                Directory.CreateDirectory(destDir);
            }
            try
            {
                string[] fileList = Directory.GetFiles(sourceDir, "*");
                foreach (string f in fileList)
                {
                    string fName = f.Substring(sourceDir.Length + 1);
                    File.Copy(Path.Combine(sourceDir, fName), Path.Combine(destDir, fName), true);
                }
            }
            catch (DirectoryNotFoundException dirNotFound)
            {
                throw new DirectoryNotFoundException(dirNotFound.Message);
            }
        }

how to use 1 line C# code implement copy folder?

Then let’s take a look at the function of copying a folder with only one line of C# code. Before starting, please add a reference: Microsoft.VisualBasic.FileIO, after adding, just write it like this. It should be noted that, don’t think that you can’t call it when you see the VB namespace, in fact, you can call it with confidence.

using Microsoft.VisualBasic.FileIO;
//In the real project, I also call this method, and only need one line of code to realize the function of copying the directory.
// The efficiency is very high, especially for copying GB-level files (znlive.com).
FileSystem.CopyDirectory(sourceDir, destDir);

how to use 1 line C# code implement copy folder?

How, is it very simple?

how to use 1 line C# code implement copy folder?
how to use 1 line C# code implement copy folder?

C# rename folder

Renaming folders through C# code is also a common function or requirement, and the common codes searched on the Internet are created by first creating a new directory, and then moving the original file to the new directory. The code that you can see is as follows shown:

//Step 1, create a new directory first, the current step is not necessary
Directory.CreateDirectory(destinationDir);
//Step 2, find the file and move it
FileInfo file = new FileInfo(srcFileName);
file.MoveTo(destFileName);

how to use 1 line C# code implement copy folder?

In the past, it was just a common example code. In fact, it was necessary to move files. Is there a way to directly rename a folder as we use the right mouse button? The answer is yes, or use the methods provided by the FileSystem class, as follows:

//This is the method of renaming the directory, let you answer, is it very simple?
FileSystem.RenameDirectory(sourceDir, destDir);

C# rename file

The need to rename a file often occurs in the upload function. The server side of the file uploaded by the user needs to rename it. Usually, similar codes commonly found on the Internet are written:

File.Move(), File.Copy() version:

string src = @"Original file path: C:\jhrs\com\old.file";
string dest = @"New file path: C:\jhrs\com\new.file";
try
{
     File.Move(src, dest);
     if (!File.Exists(src))
     {
         Console.WriteLine("jhrs.com prompt: file renamed successfully.");
     }
}
catch (IOException e)
{
     Console.WriteLine("jhrs.com prompt: {0}", e.ToString());
}
//or by copying the file
File.Copy(src, dest, true);
File.Delete(src);

how to use 1 line C# code implement copy folder?

With the above knowledge, we can deduce by analogy that we can use the methods provided by FileSystem to rename files.

//This is the method of renaming the file, let you answer, is it very simple?
FileSystem.RenameFile(oldFile, newFile);

C# moving files

The common function of file operation is to move files. Microsoft’s official website documents also give sample documents. This is the official website link:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-copy-delete-and-move-files-and-folders

Other codes are not listed here for the time being. Go straight to the answer.

//This is the method of moving the file, let you answer, is it very simple?
FileSystem.MoveFile(sourceFileName,destinationFileName)

C# move directory

how to use 1 line C# code implement copy folder?
how to use 1 line C# code implement copy folder?

When you move a directory through code, if the moved directory file is very large, it is very inefficient to recursively traverse/loop through the files in the directory to move. FileSystem provides a ready-made method that you can call to move the directory, which is very efficient after testing.

//This is the method of moving the directory, let you answer, is it very simple?
FileSystem.MoveDirectory(sourceDirectoryName, destinationDirectoryName)

Finally, you can also call the FileSystem.DeleteDirectory method to delete the directory. For other methods, look at the prompts in VS. Basically, we know what function it implements from the name. It should be noted that if the deleted file or directory has the read-only attribute, it needs to be removed.

/// <summary>
/// Recursively remove files, published on znlive.com, read-only attributes of directories
/// </summary>
/// <param name="dir"></param>
private void RemoveDirReadOnley(DirectoryInfo dir)
{
     dir.Attributes &= ~FileAttributes.ReadOnly;
     var files = dir.GetFiles();
     Parallel.ForEach(files, (f) =>
     {
         f.Attributes &= ~FileAttributes.ReadOnly;
     });
     var dires = dir.GetDirectories();
     Parallel.ForEach(dires, (f) =>
     {
         f.Attributes &= ~FileAttributes.ReadOnly;
         files = f.GetFiles();
         Parallel.ForEach(files, (m) =>
         {
             m.Attributes &= ~FileAttributes.ReadOnly;
         });
         RemoveDirReadOnley(f);
     });
}

how to use 1 line C# code implement copy folder?

Conclusion

There are still a lot of details in C#. It is a very common function to use C# for file operations. When there are a large number of files and directories that need to be moved, renamed, and copied, the efficiency issue needs to be considered; the static methods provided by the FileSystem class are basically The above covers the operations of adding, deleting, modifying, and moving files. We no longer need to write some complicated code to perform file operations. Just use the simplest method.

Leave a Comment