Файл не копируется должным образом в новое местоположение - PullRequest
0 голосов
/ 13 сентября 2018

Я написал код ac # для копирования файла csv в новое место.

Если файл уже существует в целевом расположении, файл следует удалить и вставить новый файл обратно.

Этот процесс должен повторяться и выполняться в фоновом режиме, поскольку файл CSV обновляется каждые 5минут.

Текущая проблема - даже если файл был удален по целевому пути, новый файл не будет записан обратно.

Мой код:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace filemove
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {                
        }

        public void Start()
        {                
            mysql();
        }

        static void mysql()
        {
            string fileName = "data.csv";
            string sourcePath = @"\\192.168.16.12\Users";
            string targetPath = @"C:\Users\Admin\source";

            // Use Path class to manipulate file and directory paths.
            string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
            string destFile = System.IO.Path.Combine(targetPath, fileName);

            // To copy a folder's contents to a new location:
            // Create a new target folder, if necessary.
            if (!System.IO.Directory.Exists(targetPath))
            {
                System.IO.Directory.CreateDirectory(targetPath);
            }

            // To copy a file to another location and 
            // overwrite the destination file if it already exists.
            System.IO.File.Copy(sourceFile, destFile, true);

            // To copy all the files in one directory to another directory.
            // Get the files in the source folder. (To recursively iterate through
            // all subfolders under the current directory, see
            // "How to: Iterate Through a Directory Tree.")
            // Note: Check for target path was performed previously
            //       in this code example.
            if (System.IO.Directory.Exists(sourcePath))
            {    
                string[] files = System.IO.Directory.GetFiles(sourcePath);

                // Copy the files and overwrite destination files if they already exist.
                foreach (string s in files)
                {
                    // Use static Path methods to extract only the file name from the path.
                    fileName = System.IO.Path.GetFileName(s);
                    destFile = System.IO.Path.Combine(targetPath, fileName);
                    FileInfo info = new FileInfo(destFile);
                    bool exists = info.Exists;
                    if (exists == true)
                    {
                        File.Delete(@"C:\Users\Admin\source\Bargstedt.csv");
                    }
                    else
                    { 
                        System.IO.File.Copy(s, destFile, true);                          
                    }
                }
            }
            else
            {
                Console.WriteLine("Source path does not exist!");
            }

            // Keep console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            //Console.ReadKey();
        }

        public void OnStop()
        {
        }
    }
}

Может кто-нибудь выяснить в чем ошибка?

Ответы [ 3 ]

0 голосов
/ 13 сентября 2018

File.Delete фактически не выдает никаких исключений, если файл не существует.Итак, я просто уберу проверку для существования полностью.

try {
int delay = 400;

File.Delete(@"C:\Users\Admin\source\Bargstedt.csv");
Thread.Sleep(delay); // to prevent delete and copy happening at the 
// same time.

System.IO.File.Copy(s, destFile, true);                          

}catch (IOException ex) {}

Вы также можете проверить в этом посте:

FileStream и FileSystemWatcher в C #, странный вопрос "процесс не можетполучить доступ к файлу " и ответить пользователю EventHorizon на наличие закрытых файлов.

Рекомендуется также проверить, есть ли у каталога разрешения (FileIOPermissionAccess.Write)

0 голосов
/ 13 сентября 2018

Используйте это для копирования файла, если он существует в целевом пути и с планом резервного копирования для этого существующего файла.

// To copy a file to another location and 
        // overwrite the destination file if it already exists.
        if (!File.Exists(destFile))
        {
            System.IO.File.Copy(sourceFile, destFile, true);
        }
        else
        {
            System.IO.File.Move(destFile, existingFilePath); //if file is existing and then move it to specific folder
            try
            {
                System.IO.File.Copy(sourceFile, destFile, true);
            }
            catch (Exception)
            {
                System.IO.File.Move(existingFilePath, destFile); //If anythig went wrong, old file is relocated correctly
            }
            System.IO.File.Delete(existingFilePath); // Delete old file, all is ok now.
        }
0 голосов
/ 13 сентября 2018

Я думаю, что вы хотите написать файл, даже если он был.

Вы используете:

bool exists = info.Exists;
if (exists == true)
{
    File.Delete(@"C:\Users\Admin\source\Bargstedt.csv");
}
else
{ 
    System.IO.File.Copy(s, destFile, true); 
}

Удалите остальное:

bool exists = info.Exists;
if (exists == true)
{
    File.Delete(@"C:\Users\Admin\source\Bargstedt.csv");
} 
System.IO.File.Copy(s, destFile, true);
...