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

标签 c# file

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

string source = "C:\\A\\ResultClassA.txt";
File.Move(Source, "C:\\AA");

但它总是给出这个错误信息:

访问路径被拒绝。

故障排除提示: 确保您有足够的权限访问此资源。 如果您试图访问文件,请确保它不是只读的。 获取此异常的一般帮助。

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

谢谢。 通过英雄。

最佳答案

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

string source = "C:\\A\\ResultClassA.txt";
File.Move(Source, "C:\\AA\\ResultClassA.txt");

参见 here好的 sample

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());
        }
    }
}

关于c# - 如何将txt文件移动到其他文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7157915/

相关文章:

每次保存文件时执行的 linux(和 OSX)shell 命令

c - 如何在c中读取文件并打印不同单词的数量

c# - C# 项目中的大规模重命名(重构)

c# - Outlook 加载项的弹出通知(从后台线程问题调用 Form.Show())

c# - 在 C# 中加密和解密字符串?

c++ - 在 C++ 中从在线文本文件中读取数据

android - 从内部存储的下载文件夹中打开下载的文件 (pdf)

c# - 您如何在服务之间共享 gRPC 原型(prototype)定义

c# - 在数据库中存储 X509 证书

r - 如何在R中提取文件夹的名称(序列号ID)?