C#中的File.Copy不工作

时间:2015-12-14 17:21:31

标签: c# file copy

使用File.Copy函数将文本文件从一个位置复制到另一个位置后,我尝试在另一个文本文件上完全相同的功能(我已经开始工作)无法写入。然而,奇怪的是,没有异常抛出!我知道该文件存在于

if(File.Exist(myFile))

我的档案。复制代码:

File.Copy(sourceFilePathCombined, targetFilePathCombined, true);

这适用于同一目录中的一个文件,但不适用于另一个文件。没有例外。为什么不写文件,但是其他文件被复制没有问题?

需要的人的代码:

         var indexFileDirectory = ConfigurationManager.AppSettings["Accident.IndexFileDirectory"];
         var xRefToDoList = ConfigurationManager.AppSettings["Accident.XRefToDoList"];
         var xRefToDoResult = ConfigurationManager.AppSettings["Accident.XRefToDoResult"];
         var toDoFilePath = Path.Combine(indexFileDirectory, xRefToDoResult);
         var indexFilePath = Path.Combine(indexFileDirectory , xRefToDoList);

          //Includes date-time stamp to suffix the file
        var xRefToDoResultsDateTime = DateTime.Now.ToString("yyMMddhhmmss");

        //If the directory does not exist then create it
        if (!Directory.Exists(XRefPath))
        {
            Directory.CreateDirectory(XRefPath);
        }
        var indexToStart = xRefToDoList.IndexOf(".");
        var test2 = xRefToDoList.Remove(indexToStart, 4);

        indexToStart = xRefToDoResult.IndexOf(".");
        var test3 = xRefToDoResult.Remove(indexToStart, 8);
         var xRefToDoListCombinedPath = Path.Combine(XRefPath, (test2 + "_lst" + "." + xRefToDoResultsDateTime));
         var xRefResultListCombinedPath = Path.Combine(XRefPath, (test3 + "_results" + "." + xRefToDoResultsDateTime));
         string extension = Path.GetExtension(toDoFilePath);

            try
        {
            File.Copy(indexFilePath, xRefToDoListCombinedPath, true);//THIS WORKS!

            File.Copy(toDoFilePath, xRefResultListCombinedPath, true);//this does NOT
        }
        catch (Exception ex)
        {
            var test = ex;
        }

2 个答案:

答案 0 :(得分:1)

Try using foreach to move all files

if (!System.IO.Directory.Exists(targetPath))
    System.IO.Directory.CreateDirectory(targetPath);

string[] files = Directory.GetFiles(sourcePath);

foreach (var file in files)
{
    string name = Path.GetFileName(file);
    string target = Path.Combine(targetPath, name);
    File.Copy(file, target, true);
}

答案 1 :(得分:1)

在目录中查找文件时,请务必不要将修改日期与创建日期混淆。如果它具有Date Modified值,它可能看起来没有被创建。