简体   繁体   中英

File.Copy in C# NOT Working

After using the File.Copy function to copy a text file from one location to another i try the exact same functionality (that i've already gotten to work) on another text file fails to write. However, the weird part is that there is NO EXCEPTION thrown! I know the file exists by doing

if(File.Exist(myFile))

My File.Copy code:

File.Copy(sourceFilePathCombined, targetFilePathCombined, true);

This works well for one file in the same directory, but not for the other. There is NO exception. Why won't it write the file, but the other file gets copied without issue?

Code for those who need it:

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

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

Be sure to not confuse Date Modified with Date Created when looking for the file in a directory. It may look like it didn't get created if it has a Date Modified value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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