我尝试编写一个控制台应用程序 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/