C# 檔案操作(複製、刪除和移動檔案)

C# 檔案操作(複製、刪除和移動檔案)

C# 檔案操作(複製、刪除和移動檔案)


 

資料來源:https://msdn.microsoft.com/zh-tw/library/cc148994.aspx

 

 

複製:

 string fileName = "test.txt";

        string sourcePath = @"C:\Users\Public\TestFolder";

        string targetPath =  @"C:\Users\Public\TestFolder\SubDir";

 

        // Use Path class to manipulate file and directory paths.

        string sourceFile = System.IO.Path.Combine(sourcePath, fileName);

        string destFile = System.IO.Path.Combine(targetPath, fileName);

    

     if (!System.IO.Directory.Exists(targetPath))

        {

            System.IO.Directory.CreateDirectory(targetPath);

        }

    

        // To copy a file to another location and

        // overwrite the destination file if it already exists.

        System.IO.File.Copy(sourceFile, destFile, true);


 

 

移動:

        string sourceFile = @"C:\Users\Public\public\test.txt";

        string destinationFile = @"C:\Users\Public\private\test.txt";

 

        // To move a file or folder to a new location:

        System.IO.File.Move(sourceFile, destinationFile);

 

        // To move an entire directory. To programmatically modify or combine

        // path strings, use the System.IO.Path class.

        System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");

 

    

 

刪除:

 // Delete a file by using File class static method...

        if(System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))

        {

            // Use a try block to catch IOExceptions, to

            // handle the case of the file already being

            // opened by another process.

            try

            {

                System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");

            }

            catch (System.IO.IOException e)

            {

                Console.WriteLine(e.Message);

                return;

            }

        }

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *