C# 在C中将文件从一个位置移动到另一个位置#
我使用以下代码在循环中将文件从一个位置移动到另一个位置,同时每次在循环中都创建一个新文件,但会引发以下异常:C# 在C中将文件从一个位置移动到另一个位置#,c#,file-io,C#,File Io,我使用以下代码在循环中将文件从一个位置移动到另一个位置,同时每次在循环中都创建一个新文件,但会引发以下异常: System.IO.IOException: Cannot create a file when that file already exists. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileInfo.MoveTo(String destFil
System.IO.IOException: Cannot create a file when that file already exists.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileInfo.MoveTo(String destFileName).
这是我的代码:
string strFile = strFileName;
try
{
string strFinalPath = ApplicationConfiguration.FinalInvoiceFolder;
if (!Directory.Exists(strFinalPath))
{
Directory.CreateDirectory(strFinalPath);
}
if (File.Exists(strPrintedFilePath))
{
objFile.MoveTo(strFinalPath + strFile);
}
}
catch (Exception ex2)
{
WriteLogCustom(ex2.ToString() + ex2.InnerException.ToString(), true);
}
您的代码应该如下所示
if (File.Exists(strPrintedFilePath))
{
string destinationPath = Path.Combine(strFinalPath, strFile);
if(File.Exists(destinationPath)
{
// your logic to handle situations
// when a destination file already exists
}
else
{
objFile.MoveTo(destinationPath);
}
}
试试这个
string path1 = @"C:\Users\username\Desktop\Erro1.png";
string path2 = @"C:\test\Erro1.png";
if (File.Exists(path2))
File.Delete(path2);
// Move the file.
File.Move(path1, path2);
确保目标路径具有完全权限权限,否则会出现拒绝访问错误。要将2个或更多字符串组合到一个路径,请选择更好的路径。组合(strFinalPath,strFile)哪些是文件名?使用
path
类来播放路径。它在System.IO
中可用。原因可能是,您可以尝试将objFile
中提到的文件移动到提到的位置。引发的异常是吗?如果目标路径没有足够的权限,则会发生异常。但是,与问题中的消息不符。每次都不会显示错误,假设我有10000个文件,那么所有文件都成功移动了,但还有200个文件要移动,因此不可能出现权限问题。我建议您在本地计算机上创建一个文件夹并删除该文件夹的权限,然后检查发生了什么@Hemantsonia agery与您的代码,但怎么可能,文件不应该存在,因为我创建的pdf文件在循环中使用时间和秒在文件命名,所以在移动的时候,如何可以在目标文件夹中存在相同的文件,如果我将使用这个。某些文件仍保留在源文件夹中。您可以调整此代码,如果删除else
关键字,则文件仍将被移动。我怀疑,如果您多次运行相同的代码,您已经移动的文件将导致冲突。除非每次运行都生成一个唯一的名称。