c#+php实现windows文件夹文件自动实时同步备份到linux教程

c#+php实现windows文件夹文件自动实时同步备份到linux教程

c#+php实现windows文件夹文件自动实时同步备份到linux教程

原理就是c#中利用FileSystemWatcher来监听文件夹内文件变化,发现有新增、修改、删除等操作就会上传php进行同步。

而php就只是更新服务器上的文件,授权代码自己可以加

c# windows客户端代码:

using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;

class Program
{
    // 监控的文件夹路径
    static string folderPath = @"C:\Users\UploADFOLER\";
    static void Main()
    {
        
      

        // 创建一个FileSystemWatcher实例
        FileSystemWatcher watcher = new FileSystemWatcher();

        // 设置要监控的文件夹路径
        watcher.Path = folderPath;

        // 启用监控子文件夹
        watcher.IncludeSubdirectories = true;

        // 监听文件夹中的新文件、修改、删除
        watcher.Created += OnChanged;
        watcher.Changed += OnChanged;
        watcher.Deleted += OnChanged;
        watcher.Renamed += OnRenamed;

        // 开始监控
        watcher.EnableRaisingEvents = true;

        Console.WriteLine($"Monitoring folder: {folderPath}");
        Console.WriteLine("Press Enter to exit.");
        Console.ReadLine();
    }

    private static void OnChanged(object sender, FileSystemEventArgs e)
    {
        // 等待文件完全写入
        Thread.Sleep(1000);

        // 获取变化的文件的完整路径
        string filePath = e.FullPath;

        // 处理文件上传到服务器的逻辑
        UploadFileToServer(filePath);

        Console.WriteLine($"File uploaded: {filePath}");
    }

    private static void OnRenamed(object sender, RenamedEventArgs e)
    {
        // 获取变化的文件的完整路径
        string filePath = e.FullPath;

        // 处理文件上传到服务器的逻辑
        UploadFileToServer(filePath);

        Console.WriteLine($"File uploaded (renamed): {filePath}");
    }
   

    static string GetRelativePath(string basePath, string fullPath)
    {
        Uri baseUri = new Uri(basePath);
        Uri fullUri = new Uri(fullPath);

        Uri relativeUri = baseUri.MakeRelativeUri(fullUri);
        string relativePath = Uri.UnescapeDataString(relativeUri.ToString());

        return relativePath.Replace('/', '\\');
    }

    static  void UploadFileToServer(string filePath)
    {
        try
        {
            // 上传文件到服务器的逻辑
            using (WebClient client = new WebClient())
            {
                // 服务器上传地址
                string uploadUrl = "https://example.com/upload.php";

                // 使用上传文件的文件名
                string fileName = Path.GetFileName(filePath);
                Console.WriteLine(fileName);

                string relativePath = GetRelativePath(folderPath, filePath);
                Console.WriteLine(relativePath);

              
                // 使用 HttpClient 上传文件和其他POST参数

              
                // 上传文件
                byte[] responseBytes = client.UploadFile(uploadUrl+ "?relativePath="+ relativePath, "POST", filePath);
                string response = System.Text.Encoding.UTF8.GetString(responseBytes);
                Console.WriteLine("Server Response: " + response);
                Console.WriteLine($"File {fileName} uploaded to server.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error uploading file: {ex.Message}");
        }
    }
}

  

后端服务器php

<?php
// 上传文件的目录
$uploadDir = 'uploads/';


// 确保上传目录存在
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// 处理上传的文件
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file']) && isset($_GET['relativePath'])) {
    $file = $_FILES['file'];
    $relativePath = $_GET['relativePath'];
    $relativePath=str_replace("\\","/",$relativePath);
    // 构建文件的最终路径
    $uploadPath = $uploadDir . '/' . $relativePath;

    // 确保目标目录存在
    $targetDir = dirname($uploadPath);
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    // 移动上传的文件到目标目录
    if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
        echo 'File uploaded successfully.';
    } else {
        echo 'Error uploading file.';
    }
} else {
    echo 'Invalid request.';
}
?>

{{collectdata}}

网友评论0