2014-04-04 49 views
0

我正在使用以下代码将循环中的文件从一个位置移动到另一个位置,而我每次都在循环中创建一个新文件,但引发了以下异常:将文件从一个位置移动到C#中的其他位置

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

http://www.dotnetperls.com/file-move –

+3

要将2个或更多的字符串结合到一个更好的路径Path.Combine(strFinalPath,strFile) – Relax

+0

哪些是文件的文件名? – Tinwor

回答

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

雅代与您的代码,但它怎么可能,文件不应该在那里,因为我正在使用文件命名中的时间和秒使用循环创建pdf文件,所以在移动,如何可以在目标文件夹中存在相同的文件如果我会用这个。一些文件一直保留在源文件夹中。 –

+0

你可以调整这段代码,如果你删除了'else'关键字,那么文件将被移动。我怀疑,如果您多次运行相同的代码,那么您已移动的文件将导致冲突。除非每次运行都生成一个唯一的名称。 – oleksii

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

请确保您的目标路径具有完整的权限权限,否则会导致您拒绝访问错误。

+0

是抛出的异常吗? – Jodrell

+0

如果目标路径权限不足,则会发生异常。 –

+0

但是,与问题中的“消息”不同。 – Jodrell

相关问题