如何将txt文件移动到其他文件夹?

Her*_*ero 1 c# file

我尝试编写一个控制台应用程序C#来将我的etxt文件移动到另一个文件夹.这些函数只是将文件夹A中的某些.txt文件复制到文件夹AA中

string source = "C:\\A\\ResultClassA.txt";
File.Move(Source, "C:\\AA");
Run Code Online (Sandbox Code Playgroud)

但它始终给出此错误消息:

拒绝访问该路径.

疑难解答提示:确保您具有足够的权限来访问此资源.如果您尝试访问文件,请确保它不是ReadOnly.获取此异常的常规帮助.

在"File.move"代码执行之前,我真的需要将文件夹A和文件夹B设置为"NOT ReadOnly"属性吗?成功移动后,设置为只读回来?

谢谢.由英雄.

Pre*_*gha 5

您需要指定完整路径并确保路径C:\AA存在

string source = "C:\\A\\ResultClassA.txt";
File.Move(Source, "C:\\AA\\ResultClassA.txt");
Run Code Online (Sandbox Code Playgroud)

请看这里的样品

using System;
using System.IO;
class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = @"c:\temp2\MyTest.txt";
        try 
        {
            if (!File.Exists(path)) 
            {
                // This statement ensures that the file is created,
                // but the handle is not kept.
                using (FileStream fs = File.Create(path)) {}
            }

            // Ensure that the target does not exist.
            if (File.Exists(path2)) 
            File.Delete(path2);

            // Move the file.
            File.Move(path, path2);
            Console.WriteLine("{0} was moved to {1}.", path, path2);

            // See if the original exists now.
            if (File.Exists(path)) 
            {
                Console.WriteLine("The original file still exists, which is unexpected.");
            } 
            else 
            {
                Console.WriteLine("The original file no longer exists, which is expected.");
            }           

        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)