在C#中将文件从一个位置移动到另一个位置

时间:2014-04-04 10:34:08

标签: 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 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);
}

2 个答案:

答案 0 :(得分:3)

您的代码看起来应该是这样的

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

答案 1 :(得分:0)

试试这个

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

确保您的目标路径具有完全权限权限,否则会为您提供访问被拒绝错误。

相关问题