c# - 识别新同步的文件 (WinSCP)

标签 c# .net scp winscp winscp-net

我目前正在开发一个解析应用程序,它首先从远程服务器获取.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();
            }
        }
    }
}

以上代码基于Session.SynchronizeDirectories Method WinSCP 的。

最佳答案

所以不要枚举所有 *.csv 文件。仅枚举那些已同步/下载的:

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

请参阅SynchronizationResult class .


如果需要持续同步,则需要循环运行代码或安排其频繁运行。请参阅 WinSCP 示例 Keep local directory up to date (download changed files from remote SFTP/FTP server) – 它在 PowerShell 中,但应该可以给您一个想法。

关于c# - 识别新同步的文件 (WinSCP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39588480/

相关文章:

c# - 为什么需要 EndExecuteNonQuery()?

c# - 确定互联网连接是否可用

c# - NullReferenceException 在 ASP.NET MVC 5 中使用 DropDownListFor

c# - .Net Regex 性能问题

c# - 是否有默认方法来获取成功完成的第一个任务?

.net - "SAP Connector for .NET": Generate proxies without Visual Studio 2003

c# - 如何使用来自 mssql 数据库的数据单击 C# .net 页面中包含的 JavaScript block 内的每个标记来添加信息窗口

shell - 如何让expect -c在单行而不是脚本中工作

linux - 如何在子shell中设置变量?

linux - 在后台运行 SCP 并监控进度