繁体   English   中英

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

[英]Move File From one location to other in 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);
}

您的代码应如下所示

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM