用C从FTP下载文件#

2024-04-20 09:34:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python脚本,它在FTP目录上迭代,根据文件名和所在目录将任何新文件下载到特定位置。因为我使用的FTP库行为异常,我想将它移到C#,并将它与我的表单应用程序合并。你知道吗

问题是,我似乎找不到太多的FTP在C#什么我需要的,所以我希望我可以在这里得到一些帮助。下面我已经包含了我的Python代码,因为它可能会显示出我想要做的比我的文字更好。你知道吗

def work(ftp, extensions):
    if not ftp.path.exists('/downloads'):
        ftp.mkdir('/downloads')
    ftp.chdir('/downloads')
    os.chdir('Z:\\')
    r = re.compile(r'\./(.+?)/.+?(\d+?)/.+?E?(\d{2})\..+(\..+?$)')
    for root, dirs, files in ftp.walk('.'):
        for file in files:
            _, ext = os.path.splitext(file)
            if ext in extensions:
                    file_path = ftp.path.join(root, file)
                    date_stripped_file_path = ftp.path.join(root, re.sub(r'\.20[12]\d', '', file))
                    local_file_path = r.sub(r'./\1/\2/\1 S0\2E\3\4', date_stripped_file_path)
                    if download(ftp, file_path, local_file_path, 'TV'):
                        m = r.match(date_stripped_file_path)
                        insert_into_database(m.group(1), int(m.group(2)), int(m.group(3)), os.path.abspath(local_file_path))

def download(ftp, source, target, type):
    if (not os.path.isfile(target)) or \
        os.path.getsize(target) < ftp.path.getsize(source):
        file_name = os.path.splitext(os.path.basename(target))[0]
        print(f'{get_timestamp()}... Downloading: {file_name}')
        # Create dir if not exists
        dirname = os.path.dirname(target)
        if not (os.path.exists(dirname) and os.path.isdir(dirname)):
            os.makedirs(dirname)
        try:
            def display_progress(chunk):
                bar.update(len(chunk))

            bar = click.progressbar(length=ftp.path.getsize(source))
            ftp.download(source, target, callback=display_progress)
            print('')
        except Exception as e:
            print(f'{get_timestamp()}... Dowmload failed')
            log_error(e, True)
        else:
            ftp.remove(source)
            return True
    else:
        ftp.remove(source)
        return True

我有一个无限期的work,每10分钟运行一次。简言之,我需要在C#中找到的唯一东西是for root, dirs, files in ftp.walk('.')的等价物

编辑:我更喜欢使用.NET中包含的库,但是如果这变得复杂,我愿意使用外部库。你知道吗


Tags: pathinsourcetargetifosdownloadsdef