移动文件时出现异常
Exception while moving files
嘿,最近我一直在尝试将文件从一个文件夹移动到另一个文件夹,但错误不断出现。
loacation 和 destination 文件夹都已创建,location 有几个 .txt 文件
这是我试过的方法:
string path = @"C:\TESTmove\path";
string path2 = @"C:\TESTmove\destiny";
if (Directory.Exists (path))
{
foreach (string filename in Directory.GetFiles(path))
{
File.Move (filename, path2);
//Console.WriteLine (filename);
}
}
else
{
Console.WriteLine("Wrong place");
}
我收到这个错误:
Cannot create a file when that file already exists.
您正在目录路径 "C:\TESTmove" 中创建名为 "destiny" 的同一文件。 (这不是您想要的,但这基本上就是您发布的代码要做的。)
而是在将文件移动到新位置时包含文件名。
File.Move(filename, Path.Combine(path2, Path.GetFileName(filename)));
你的代码是错误的,你是说:
string path2 = @"C:\TESTmove\destiny";
string filename = @"C:\TESTmove\path\test1.txt";
File.Move (filename, path2);
path2 应包含路径和文件名。
例如应该是这样
string sourceFile = @"C:\TESTmove\path\whatever.txt";
string destinationFile = @"C:\TESTmove\whatever.txt";
System.IO.File.Move(sourceFile, destinationFile);
没有魔法,File.Move 需要知道您要将哪个文件移动到哪个文件(而不仅仅是位置)。
嘿,最近我一直在尝试将文件从一个文件夹移动到另一个文件夹,但错误不断出现。 loacation 和 destination 文件夹都已创建,location 有几个 .txt 文件
这是我试过的方法:
string path = @"C:\TESTmove\path";
string path2 = @"C:\TESTmove\destiny";
if (Directory.Exists (path))
{
foreach (string filename in Directory.GetFiles(path))
{
File.Move (filename, path2);
//Console.WriteLine (filename);
}
}
else
{
Console.WriteLine("Wrong place");
}
我收到这个错误:
Cannot create a file when that file already exists.
您正在目录路径 "C:\TESTmove" 中创建名为 "destiny" 的同一文件。 (这不是您想要的,但这基本上就是您发布的代码要做的。)
而是在将文件移动到新位置时包含文件名。
File.Move(filename, Path.Combine(path2, Path.GetFileName(filename)));
你的代码是错误的,你是说:
string path2 = @"C:\TESTmove\destiny";
string filename = @"C:\TESTmove\path\test1.txt";
File.Move (filename, path2);
path2 应包含路径和文件名。
例如应该是这样
string sourceFile = @"C:\TESTmove\path\whatever.txt";
string destinationFile = @"C:\TESTmove\whatever.txt";
System.IO.File.Move(sourceFile, destinationFile);
没有魔法,File.Move 需要知道您要将哪个文件移动到哪个文件(而不仅仅是位置)。