簡體   English   中英

識別新同步的文件 (WinSCP)

[英]Recognize newly synchronized files (WinSCP)

我目前正在開發一個解析應用程序,它首先從遠程服務器獲取.csv文件,然后將其同步到本地服務器。 同步后,從本地路徑下載的文件將被解析,然后插入到 SQL 數據庫中。 如果有從遠程服務器添加的新文件(然后同步到本地服務器),應用程序如何知道只解析那些特定的新文件(防止重新解析和重新插入舊的 .csv 文件)已經解析)?

到目前為止我的代碼:

public static int Main()
{
    try
    {
        // Setup session options
        SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Scp,
            HostName = hostName,
            UserName = userName,
            Password = passWord,
            SshHostKeyFingerprint = sshHostKey
        };

        using (Session session = new Session())
        {
            // Will continuously report progress of synchronization
            session.FileTransferred += FileTransferred;

            // Connect
            session.Open(sessionOptions);

            // Synchronize files
            SynchronizationResult synchronizationResult;
            synchronizationResult =
                session.SynchronizeDirectories(
                    SynchronizationMode.Local, localPath, remotePath, false);

            // Throw on any error
            synchronizationResult.Check();

            Run();
        }
        return 0;
    }
    catch (Exception e)
    {
        Console.WriteLine("Error: {0}", e);
        Console.ReadLine();
        return 1;
    }
}

這在同步文件時處理事件:

private static void FileTransferred(object sender, TransferEventArgs e)
{
    if (e.Error == null)
    {
        Console.WriteLine("Upload of {0} from remote to local server succeeded", e.FileName);
    }
    else
    {
        Console.WriteLine("Upload of {0} from remote to local server failed: {1}", e.FileName, e.Error);
    }

    if (e.Chmod != null)
    {
        if (e.Chmod.Error == null)
        {
            Console.WriteLine("Permisions of {0} set to {1}", e.Chmod.FileName, e.Chmod.FilePermissions);
        }
        else
        {
            Console.WriteLine("Setting permissions of {0} failed: {1}", e.Chmod.FileName, e.Chmod.Error);
        }
    }
    else
    {
        Console.WriteLine("Permissions of {0} kept with their defaults", e.Destination);
    }

    if (e.Touch != null)
    {
        if (e.Touch.Error == null)
        {
            Console.WriteLine("Timestamp of {0} set to {1}", e.Touch.FileName, e.Touch.LastWriteTime);
        }
        else
        {
            Console.WriteLine("Setting timestamp of {0} failed: {1}", e.Touch.FileName, e.Touch.Error);
        }
    }
    else
    {
        // This should never happen during "local to remote" synchronization
        Console.WriteLine("Timestamp of {0} kept with its default (current time)", e.Destination);
    }
}

這將解析.csv文件的內容。 同步后發生。

public static void Run()
{
    dataTable();

    List<string> items = new List<string>();

    foreach (string file in Directory.EnumerateFiles(localPath, "*.csv"))
    {
        if (file.Contains("test"))
        { }
        else
        {
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    while (!sr.EndOfStream)
                        items.Add(sr.ReadLine());

                    foreach (string item in items)
                    {
                        var row = dt.NewRow();
                        string[] columnValues = item.Split(',');
                        int column = 3;

                        for (int a = 0; a < columnValues.Length; a++)
                        {
                            string date = columnValues[29] + " " + columnValues[28];
                            row[col[1].ColumnName] = DateTime.Parse(date);
                            string test = file.Split(new[] { splitVal }, StringSplitOptions.None)[1];
                            row[col[2].ColumnName] = test.Split('.')[0];

                            if (a >= 54)
                            { }
                            else
                            {
                                if (string.IsNullOrEmpty(columnValues[a]))
                                {
                                    row[col[column].ColumnName] = DBNull.Value;
                                }
                                else
                                {
                                    try
                                    {
                                        try
                                        {
                                            row[col[column].ColumnName] = columnValues[a].Trim();
                                        }
                                        catch
                                        {
                                            try
                                            {
                                                row[col[column].ColumnName] = Convert.ToDouble(columnValues[a].Trim());
                                            }
                                            catch
                                            {
                                                row[col[column].ColumnName] = int.Parse(columnValues[a].Trim());
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("Error [" + col[column].ColumnName + "]:" + ex.ToString());
                                        //row[col[column].ColumnName] = DBNull.Value;
                                    }
                                }
                            }

                            column++;
                        }
                        dt.Rows.Add(row);
                    }

                    using (SqlConnection con = new SqlConnection(consstring))
                    {
                        using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                        {
                            //Set the database table name
                            sqlBulkCopy.DestinationTableName = dbTable;
                            con.Open();
                            try
                            {
                                sqlBulkCopy.WriteToServer(dt);
                                Console.WriteLine(file.Substring(file.LastIndexOf('\\') + 1) + " uploaded in the database\n");
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(file.Substring(file.LastIndexOf('\\') + 1) + " cannot be uploaded to database. " + ex.ToString());
                            }
                            con.Close();
                        }
                    }
                    sr.Dispose();
                    sr.Close();
                }

                fs.Dispose();
                fs.Close();
            }
        }
    }
}

以上代碼基於 WinSCP 的Session.SynchronizeDirectories 方法

所以不要枚舉所有*.csv文件。 僅枚舉同步/下載的那些:

foreach (TransferEventArgs transfer in synchronizationResult.Downloads)
{
    string file = transfer.Destination;
    ...
}
 

請參閱SynchronizationResult


如果需要持續同步,則需要循環運行代碼或安排它以頻繁的間隔運行。 請參閱 WinSCP 示例使本地目錄保持最新(從遠程 SFTP/FTP 服務器下載更改的文件) ——它在 PowerShell 中,但應該給你一個想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM